/**
* La documentation de ce script n'est pas développée ici, on fera référence à la documentation de completionMEC.js
**/

var dn="www.easyvols.org";
//var dn="seoul.mev.lfr:85";
var completionMECURLRoot;
switch(window.lang){
	case "es_ES":
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/es_ES";
		break;
	case "it_IT":
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/it_IT";
		break;
	case "en_GB":
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/en_GB";
		break;
	case "de_DE":
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/de_DE";
		break;
	case "fr_FR":
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/fr_FR";
		break;
	default:
		completionMECURLRoot="http://"+dn+"/base/rjs/completion/MEC/fr_FR";
		break;
}

var completionMECRJS=new RemoteScript(completionMECURLRoot+"/load_default.rjs");

// Hauteur des lignes pour les MSIE<=6.9
var MSIE6_LINE_HEIGHT=20;
var MSIE6_LINE_WIDTH=300;



function CompletionMEC(elementText,elementData,positionDiv,maxAddressesInList) {
	this.poolIndex=completionMECPool.add(this);
	this.status="off";
	this.elementText=elementText;
	this.elementText.setAttribute("autocomplete","off");
	if(genericNavigator.navigator.id==MSIE){
		addJavascriptToAttribute(this.elementText,"onkeydown","completionMECPool.get("+this.poolIndex+").toucheDown(event);");
		addJavascriptToAttribute(this.elementText,"onkeyup","completionMECPool.get("+this.poolIndex+").toucheUp(event);");
		addJavascriptToAttribute(this.elementText,"onfocus","completionMECPool.get("+this.poolIndex+").updatePropositions(event);");
		addJavascriptToAttribute(this.elementText,"ondeactivate","completionMECPool.get("+this.poolIndex+").delayedHidePropositions(500);");
	}
	else{
		addJavascriptToAttribute(this.elementText,"onkeydown","return completionMECPool.get("+this.poolIndex+").toucheDown(event);");
		addJavascriptToAttribute(this.elementText,"onkeyup","return completionMECPool.get("+this.poolIndex+").toucheUp(event);");
		addJavascriptToAttribute(this.elementText,"onfocus","return completionMECPool.get("+this.poolIndex+").updatePropositions(event);");
		addJavascriptToAttribute(this.elementText,"onblur","completionMECPool.get("+this.poolIndex+").delayedHidePropositions(500);");
	}
	this.elementData=elementData;
	this.propositionsDiv=document.createElement("DIV");
	this.propositionsDiv.style.visibility="hidden";
	this.propositionsDiv.className="completionMEC";
	if(genericNavigator.navigator.id==MSIE&&genericNavigator.navigator.version<=6.9){
		this.propositionsDiv.style.width=MSIE6_LINE_WIDTH+"px";
		this.propositionsDiv.style.padding="5px";
	}
	positionDiv.appendChild(this.propositionsDiv);

	var DEFAULT_MAX_ADDRESSES_IN_LIST=6;
	this.maxAddressesInList=DEFAULT_MAX_ADDRESSES_IN_LIST;
	if(maxAddressesInList){
		this.maxAddressesInList=maxAddressesInList;
	}

	this.propositions=[];
	this.lineSelected=-1;
	this.lines=[];
	this.pageIndex=0;	
	this.updating=false;

	this.toucheUp=function(event) {
		if(!event){return;}
		if(shouldUpdatePropositions(event)){
			this.updatePropositions(event);
		}
		return true;
	};

	this.toucheDown=function(event) {
		if(!event){return;}
		return completionToucheDown(this, event);
	};

	this.updatePropositions=function(event) {
		if(!event){return;}
		if(this.updating){return;}
		this.updating=true;
		if(event.type!=="focus"){
			this.elementData.value="";
		}
		var elementTextValue=this.elementText.value;
		if(elementTextValue.length>=3){
			var prefix=getPrefix(elementTextValue);
			this.propositions=[];
			var completionObjet=this;
			var onAfterUpdate=function(){
					//console.log('/load_'+prefix+'.rjs reçu : '+completionObjet.propositions.length+' proposition(s)');
					completionObjet.updating=false;
				};
			completionMECRJS.invoke(completionMECURLRoot+"/load_"+prefix+".rjs","initMECPropositions("+this.poolIndex+")", onAfterUpdate);
		}
		else{
			this.hidePropositions();
			this.updating=false;
		}
		return true;
	};

	this.showPropositions=function() {
		// Si le div de positionnement des propositions n'est pas présent, inutile d'aller plus loin
		if(!this.propositionsDiv){return;}
		
		// On vide le div de positionnement de tous les éléments précédements affichés
		var node=this.propositionsDiv.lastChild;
		while(node){
			this.propositionsDiv.removeChild(node);
			node=this.propositionsDiv.lastChild;
		}

		// On calcule l'expression régulière qui correspond au texte tapé par l'utilisateur
		var regExp=new RegExp("^"+formateText(this.elementText.value).replace(/\s+/,"\\s+")+".*");

		// Cette variable va tenir le décompte des lignes des addresses affichées
		var line=0;
		this.lines=[];
		// On passe en revue toutes les propositions adresses
		for(var i=0;i<this.propositions.length;i++){
			// Si la proposition adresses matche avec le champ texte
			if(this.propositions[i].matches(regExp)){
				addJavascriptToAttribute(this.propositions[i].div,"onmouseover","completionMECPool.get("+this.poolIndex+").selectLine("+line+")");
				addJavascriptToAttribute(this.propositions[i].div,"onmousedown","completionMECPool.get("+this.poolIndex+").validLine("+line+")");
				this.lines[line]=this.propositions[i];
				// On insère l'adresse dans le tableau des lignes
				line++;

				// Initialisation des variables utilisé pour la mise en gras dans les proposition du texte saisie.
				var reg=new RegExp("("+formateText(this.elementText.value).replace(/\s+/,"\\s+")+")", "gi");
				var chaine = this.propositions[i].div.childNodes[0].nodeValue;
				// Creation d'une chaine sans accent pour la mise en évidance.
				chaineSansAccent=replaceAccents(chaine);
				// Modification du DOM pour mettre en évidance la correspondance entre le texte fourni et celui proposé.
				this.propositions[i].div.childNodes[0].nodeValue="";
				modifDomWhithSearch(chaine, chaineSansAccent, this.elementText.value, this.propositions[i].div, reg);
				this.propositionsDiv.appendChild(this.propositions[i].div);

				if(genericNavigator.navigator.id==MSIE&&genericNavigator.navigator.version<=6.9){
					this.propositions[i].div.style.height=MSIE6_LINE_HEIGHT+"px";
					this.propositions[i].div.style.width=MSIE6_LINE_WIDTH+"px";
				}
			}
		}
		// Par défaut on n'a pas de ligne sélectionnée (-1), tout action sur les flêches du clavier va faire apparitre la selection grâce aux tests
		// sur this.lineSelected dans les méthodes decreaseSelectedPosition() ou increaseSelectedPosition() 
		this.hidePage();
		this.lineSelected=-1;
		this.pageIndex=0;	
		this.showPage();

		if(this.propositions.length>0&&this.propositionsDiv&&this.propositionsDiv.lastChild){
			this.status="on";
			showPropositionsElement(this.propositionsDiv, line);
		}
		else{
			this.hidePropositions();
		}
	};

	this.hidePropositions=function() {
		this.status="off";
		hidePropositionsElement(this.propositionsDiv);
	};

	this.delayedHidePropositions=function(delay){
		window.setTimeout('completionMECPool.get('+this.poolIndex+').hidePropositions();', delay);
	};

	this.updatePage=function() {
		// On détermine l'éventuel nouveau pageIndex
		var newPageIndex=Math.floor(this.lineSelected/this.maxAddressesInList);
		// S'il a changé on cache la page courante et on affiche la nouvelle
		if(this.pageIndex!=newPageIndex){
			this.hidePage();
			this.pageIndex=newPageIndex;
			this.showPage();
		}
	};

	this.showPage=function() {
		for(var i=this.pageIndex*this.maxAddressesInList;i<(this.pageIndex+1)*this.maxAddressesInList&&i<this.lines.length&&i>=0;i++){
			this.lines[i].div.style.display="block";
		}
	};

	this.hidePage=function() {
		for(var i=this.pageIndex*this.maxAddressesInList;i<(this.pageIndex+1)*this.maxAddressesInList&&i<this.lines.length&&i>=0;i++){
			this.lines[i].div.style.display="none";
		}
	};
	
	this.decreaseSelectedProposition=function() {
		this.deselectProposition();
		this.lineSelected--;
		if(this.lineSelected<0){
			this.lineSelected=this.lines.length-1;
		}
		this.selectProposition();
	};

	this.increaseSelectedProposition=function() {
		this.deselectProposition();
		this.lineSelected++;
		if(this.lineSelected>=this.lines.length){
			if(this.lines.length>0){
				this.lineSelected=0;
			}
			else{
				this.lineSelected=-1;
			}
		}
		this.selectProposition();
	};

	this.selectProposition=function() {
		if(this.lines[this.lineSelected]){
			addClass(this.lines[this.lineSelected].div,"selected");
		}
	};

	this.deselectProposition=function() {
		if(this.lines[this.lineSelected]){
			removeClass(this.lines[this.lineSelected].div,"selected");
		}
	};

	this.selectLine=function(line) {
		this.deselectProposition();
		this.lineSelected=line;
		if(this.lineSelected>=this.lines.length){
			if(this.lines.length>0){
				this.lineSelected=0;
			}
			else{
				this.lineSelected=-1;
			}
		}
		else if(this.lineSelected<0){
			this.lineSelected=this.lines.length-1;
		}
		this.selectProposition();
	};
	
	this.validLine=function(line){
		this.elementText.value=this.lines[line].ville+" ["+this.lines[line].alias+"]";
		this.elementData.value=this.lines[line].data;
		// Par défaut, les adresses ne sont pas visibles car il faut tester leur page d'appartenance
		this.hidePropositions();
	};

}

/**
 * Une propriété 'data' est créée à partir des infos disponibles :
 *  - dans le meilleur des cas l'identifiant et l'alias de l'adresse sont insérés dedans (ex.: "l:4437|t:Aéroport Roissy - Charles De Gaulle")
 *  - si l'identifiant de l'adresse manque, on utilise le texte (alias de l'adresse)
 * REMARQUE : on part du principe de l'alias de l'adresse existe toujours
 */
function PropositionMECAdresse(alias,ville,pays,id) {
	this.alias=alias;
	this.ville=ville;
	this.pays=pays;
	this.id=id;
	if(this.id){
		this.data="l:"+this.id+"|t:"+this.alias;
	}
	else{
		this.data=this.alias;
	}
	this.div=document.createElement("DIV");
	this.div.className="propositionAdresse";
	this.div.appendChild(document.createTextNode(alias+", "+ville+", "+pays));
	this.div.style.display="none";
	this.index=-1;
	this.keywords=[];
}
PropositionMECAdresse.prototype={
	add: function(kw){
		this.keywords.push(kw);
	},
	matches: function(_re){
		if(textMatch(this.alias,_re)){return true;}
		if(textMatch(this.ville,_re)){return true;}
		if(textMatch(this.pays,_re)){return true;}
		for(var i=this.keywords.length;i--;){
			if(textMatch(this.keywords[i],_re)){return true;}
		}
		return false;
	}
};


var completionMECPool={
	pool: [],
	add: function(completion){
		this.pool.push(completion);
		return this.pool.length-1;
	},
	get: function(poolIndex){
		return this.pool[poolIndex];
	}
};
