String.prototype.trim = function()
{ return this.replace(/(^\s*)|(\s*$)/g, ""); }

//Variables globales
var _xmlHttp = null; //l'objet xmlHttpRequest utilis?our contacter le serveur
var _adresseRecherche = "/server2.php" //l'adresse ?nterroger 
var divCompleteWidth = 0; //largeur div de completion, calcul?plus tard
var debug = 0;
var nbCarB4Completion = 2;

var indexListe = -1;
var maxItems;
var indiceMaxTitre = -1;
var indiceMaxReal = -1;
var nbTitreMore = 0;
var nbRealMore = 0;

oldSaisie = null;
var chpSaisie; //l'id du champ de saisie, affecte ds initAjax

function initAjax(idInput){
//traceIt("init "+idInput);
	chpSaisie = idInput;
	placeDivCompletion();
	document.getElementById(idInput).onkeydown = nav_touche;
	checkSaisie(idInput);
}

//on check si la saisie a chang?oute les 200ms, si oui alors on requete le xml
//si le champ est vide on requete pas
function checkSaisie(textFieldId){
if (document.getElementById("d").value=="0"){
	if (document.getElementById(textFieldId).value.trim().length<nbCarB4Completion){
		document.getElementById("complete").style.display = "none";
	}
	else if (document.getElementById(textFieldId).value!=oldSaisie){
		oldSaisie=document.getElementById(textFieldId).value;
	//	traceIt(document.getElementById(textFieldId).value.trim());
		sendHttp(document.getElementById(textFieldId).value.trim());	
	}
}
	setTimeout("checkSaisie('"+textFieldId+"')",1000);

}

// retourne un objet xmlHttpRequest.
// m?ode compatible entre tous les navigateurs (IE/Firefox/Opera)
function getXMLHTTP(){
  var xhr=null;
  if(window.XMLHttpRequest) // Firefox et autres
  xhr = new XMLHttpRequest();
  else if(window.ActiveXObject){ // Internet Explorer
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e1) {
        xhr = null;
      }
    }
  }
  else { // XMLHttpRequest non support?ar le navigateur
    alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
  }
  return xhr;
}

//envoie la requete
function sendHttp(valeur){
 if(_xmlHttp&&_xmlHttp.readyState!=0){
    _xmlHttp.abort()
  }
  _xmlHttp=getXMLHTTP();
		
  if(_xmlHttp){
    //appel ?'url distante
    _xmlHttp.open("GET",_adresseRecherche+"?debut="+valeur,true);
	//alert(_adresseRecherche);
//traceIt("sendHTTP url ="+_adresseRecherche+"?debut="+valeur);
    _xmlHttp.onreadystatechange=function() {
//traceIt("- sendHTTP readyState="+_xmlHttp.readyState+"/respXML="+_xmlHttp.responseXML+"/status="+_xmlHttp.status);
	if(_xmlHttp.readyState==4 && _xmlHttp.responseXML) {
	
		var optionsTitre =  _xmlHttp.responseXML.getElementsByTagName("titre"); 
		var options2Titre =  _xmlHttp.responseXML.getElementsByTagName("titre2");
		var optionsLogo =  _xmlHttp.responseXML.getElementsByTagName("logo"); 
		var options2Logo =  _xmlHttp.responseXML.getElementsByTagName("logo2");
		
		var str_options = "";
//traceIt("-nb res = "+optionsTitre.length+" /valeur="+valeur);
//traceIt("-nb res2 = "+options2Titre.length+" /valeur="+valeur);
		if (optionsTitre.length!=0 || options2Titre.length!=0){
//traceIt("in ze if");		
			document.getElementById("complete").style.display = "block";
			var maxWidth = 0;
			document.getElementById("spanWidth").innerHTML = "Film(s) de ce r&eacute;alisateur ou avec cet acteur";
			var w = document.getElementById("spanWidth").offsetWidth;
			if (w>maxWidth) maxWidth=w;
			document.getElementById("spanWidth").innerHTML = "Film(s) avec ce titre";
			var w = document.getElementById("spanWidth").offsetWidth;
			if (w>maxWidth) maxWidth=w;
			
			maxItems = 0;
			indiceMaxTitre = -1;
			indiceMaxReal = -1;
			str_options += "<ul id='listechoix'>";
			//liste titre
			str_options += "<li class='lientete'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Film(s) avec ce titre</li>";
			var indiceLimiteOption = optionsTitre.length;
			if (optionsTitre.length==0){
				str_options +=  "<li class='liunselected'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Aucun r&eacute;sultats</li>";
			}
			else if (optionsTitre.length<6){
				for (var i=0; i < optionsTitre.length ; i++) {
					document.getElementById("spanWidth").innerHTML = optionsTitre[i].firstChild.data;
					var w = document.getElementById("spanWidth").offsetWidth;
//traceIt(document.getElementById("spanWidth").innerHTML+" = "+w);
					if (w>maxWidth) maxWidth=w;
					var titre = optionsTitre[i].firstChild.data;
					var logo = optionsLogo[i].firstChild.data;
				//	if (i==0) str_options += "<ul id='listechoix'>";
					str_options +=  "<li class='liunselected' id='opt"+i+"' onclick='clickValue(this)' onMouseOver='selectMouse("+i+")'><img border='0' src='/img/mini-"+logo+"'>&nbsp;"+titre+"</li>";
//traceIt("--------"+options[i].firstChild.data);
				}
				maxItems += optionsTitre.length;
			}
			else { //>6
				for (var i=0; i < 5; i++) {
					document.getElementById("spanWidth").innerHTML = optionsTitre[i].firstChild.data;
					var w = document.getElementById("spanWidth").offsetWidth;
//traceIt(document.getElementById("spanWidth").innerHTML+" = "+w);
					if (w>maxWidth) maxWidth=w;
					//alert(w);
					var titre = optionsTitre[i].firstChild.data;
					var logo = optionsLogo[i].firstChild.data;
					if (i==0 && optionsTitre.length==0) str_options += "<ul id='listechoix'>";
					str_options +=  "<li class='liunselected' id='opt"+i+"' onclick='clickValue(this)' onMouseOver='selectMouse("+i+")'><img border='0' src='/img/mini-"+logo+"'>&nbsp;"+titre+"</li>";
//traceIt("--------"+options[i].firstChild.data);
				}
				//str_options +=  "<li class='liunselected' id='opt5' onmouseover='selectMouseListe(this,1)' onmouseout='resetMouseListe(this,"+(optionsTitre.length-5)+")'><img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+(optionsTitre.length-5)+") restants</li>";
				str_options +=  "<li class='liunselected' id='opt5' onmouseover='selectMouseListe(1)' onmouseout='resetMouseListe(1)'><div id='dl11' class='liunselected'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+(optionsTitre.length-5)+") restants</div><div id='dl12' class='liselectedCursor' style='display:none;' onclick='openResultats(0);'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats</div></li>";
				nbTitreMore = (optionsTitre.length-5);
				indiceMaxTitre = 5;
				maxItems += 6;
				indiceLimiteOption = 6;
			} 
			str_options += "</ul><ul>"
//traceIt("stroptions1 "+str_options);
			//liste acteur realisateur
			str_options += "<li class='lientete'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Films de ce r&eacute;alisateur ou avec cet acteur</li>";
			if (options2Titre.length==0){
				str_options +=  "<li class='liunselected'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Aucun r&eacute;sultats</li>";
			}
			else if (options2Titre.length<6){
				for (var j=0; j < options2Titre.length; j++) {
					document.getElementById("spanWidth").innerHTML = options2Titre[j].firstChild.data;
					var w = document.getElementById("spanWidth").offsetWidth;
					//if (options2Titre.snapshotItem(j).textContent.indexOf("Lucky")>0) alert(w);
					//alert(w);
//traceIt(document.getElementById("spanWidth").innerHTML+" = "+w);
					if (w>maxWidth) maxWidth=w;
					//if (j-optionsTitre.length==0) str_options += "<ul id='listechoix'>";
					var titre = options2Titre[j].firstChild.data;
					var logo = options2Logo[j].firstChild.data;
					str_options +=  "<li class='liunselected' id='opt"+(j+indiceLimiteOption)+"' onclick='clickValue(this)' onMouseOver='selectMouse("+(j+indiceLimiteOption)+")'><img border='0' src='/img/mini-"+logo+"'>&nbsp;"+titre+"</li>";
//traceIt("---"+j+"=-----"+options2[j].firstChild.data);
				}
				maxItems += options2Titre.length;
				//alert("ds fonction2 "+maxItems);
			}
			else {
				for (var j=0; j < 5; j++) {
					document.getElementById("spanWidth").innerHTML = options2Titre[j].firstChild.data;
					var w = document.getElementById("spanWidth").offsetWidth;
//traceIt(document.getElementById("spanWidth").innerHTML+" = "+w);
					if (w>maxWidth) maxWidth=w;
					if (j-optionsTitre.length==0) str_options += "<ul id='listechoix'>";
					var titre = options2Titre[j].firstChild.data;
					var logo = options2Logo[j].firstChild.data;
					str_options +=  "<li class='liunselected' id='opt"+(j+indiceLimiteOption)+"' onclick='clickValue(this)' onMouseOver='selectMouse("+(j+indiceLimiteOption)+")'><img border='0' src='/img/mini-"+logo+"'>&nbsp;"+titre+"</li>";
//traceIt("--------"+options[i].firstChild.data);
				}
				//str_options +=  "<li class='liunselected' id='opt"+(j+indiceLimiteOption)+"' onmouseover='selectMouseListe(this,2)' onmouseout='resetMouseListe(this,"+(options2Titre.length-5)+")'><img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+(options2Titre.length-5)+") restants</li>";
				str_options +=  "<li class='liunselected' id='opt"+(j+indiceLimiteOption)+"' onmouseover='selectMouseListe(2)' onmouseout='resetMouseListe(2)'><div id='dl21' class='liunselected'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+(options2Titre.length-5)+") restants</div><div id='dl22' class='liselectedCursor' style='display:none;' onclick='openResultats(20);'><img src='/img/px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats</div></li>";
				nbRealMore = (options2Titre.length-5);
				maxItems += 6;
				indiceMaxReal = j+indiceLimiteOption;
			}	
			str_options += "</ul>";
			divCompleteWidth = maxWidth+65; //15 de rab et 50 de logo
			document.getElementById("complete").style.width = divCompleteWidth;
//traceIt("-final complete width="+divCompleteWidth);
//traceIt("-final complete offsetWidth="+document.getElementById("complete").offsetWidth);
			//alert("divCompleteWidth="+divCompleteWidth+" left de itext="+getLeft(document.getElementById(chpSaisie))+" largeur itext="+document.getElementById(chpSaisie).offsetWidth+" gauche complete="+((getLeft(document.getElementById(chpSaisie))+document.getElementById(chpSaisie).offsetWidth)-divCompleteWidth)+"px");
//traceIt("left div complete="+getLeft(document.getElementById(chpSaisie)));			
//traceIt("left completion = "+(getLeft(document.getElementById(chpSaisie))+document.getElementById(chpSaisie).offsetWidth)-divCompleteWidth+"px");
traceIt("left global="+getLeft(document.getElementById("ntv_global")));
			var gauche = getLeft(document.getElementById(chpSaisie));	//(getLeft(document.getElementById(chpSaisie))+document.getElementById(chpSaisie).offsetWidth)-divCompleteWidth;
traceIt("gauche="+gauche);
			//alert(getLeft(document.getElementById(chpSaisie))+"/"+document.getElementById(chpSaisie).offsetWidth+"/"+divCompleteWidth);
			//if (window.XMLHttpRequest) // Firefox et autres
			if (!window.ActiveXObject)
			//	gauche += 40;
traceIt("IE gauche ="+gauche);
			document.getElementById("complete").style.left = gauche+"px";
				
		}
		else {
 			document.getElementById("complete").style.display = "none";
 		}
 		document.getElementById("complete").innerHTML = str_options;
      }
      
    }
    // envoi de la requ?
    _xmlHttp.send(null)
  }
}

// tourne en permanence pour sugg?r suite ?n changement du champ texte
function mainLoop(){
  _currentInputFieldValue = _inputField.value;
  if(_oldInputFieldValue!=_currentInputFieldValue){
    var valeur=escapeURI(_currentInputFieldValue);
    var suggestions=_resultCache[_currentInputFieldValue];
    if(suggestions){ // la r?nse ?it encore dans le cache
      metsEnPlace(valeur,suggestions)
    }else{
      callSuggestions(valeur) // appel distant
    }
    _inputField.focus()
  }
  _oldInputFieldValue=_currentInputFieldValue;
  setTimeout("mainLoop()",200); // la fonction se red?enchera dans 200 ms
  return true
}
//DEBUG
function traceIt(txt){
	if (debug==1)
		document.getElementById("trace").innerHTML = txt+"<br>"+document.getElementById("trace").innerHTML;
}

//POSITIONNEMENT DE LA DIV
// calcule le décalage gauche
function calculateOffsetLeft(r){
  //return calculateOffset(r,"offsetLeft")
  return calculateOffset(r,"offsetRight");
}

// calcule le décalage vertical
function calculateOffsetTop(r){
  return calculateOffset(r,"offsetTop")
}

function calculateOffset(r,attr){
  var kb=0;
  while(r){
    kb+=r[attr];
    r=r.offsetParent;
  }
  return kb;
}

function placeDivCompletion(){	//appelée en fin de page
//traceIt("placediv top="+document.getElementById(chpSaisie).offsetHeight);
	document.getElementById("complete").style.top = calculateOffsetTop(document.getElementById(chpSaisie))+document.getElementById(chpSaisie).offsetHeight+"px";
//	alert(document.getElementById("complete").style.top);
}

function clickValue(obj){
	var html = document.getElementById("opt"+indexListe).innerHTML;
	//on escape le + "a la main"
	html = html.substring(html.indexOf(";")+1).replace("+","@_@");
	document.location = "/resultats.php?m=0&s="+html;
}

//GESTION DES TOUCHES
function nav_touche(keyStroke){
	if (document.getElementById("d").value==0){
		code_touche = (!document.all) ? keyStroke.which : event.keyCode;
		if (code_touche==40){
			parcoursListeDown();
			return false;
		}
		else if (code_touche==38){
			parcoursListeUp();
			return false;
		}
		else if (code_touche==13){
			parcoursListeEnter();
			return false;
		}
		else {
			indexListe = -1;
		}
	}
}

function parcoursListeDown(){
	if (indexListe!=maxItems-1){
		indexListe++;
		for (var j=0;j<maxItems;j++){
			document.getElementById("opt"+j).className = "liunselected";
		}
		//alert(indexListe+"/"+maxItems);
		if (maxItems!=0) document.getElementById("opt"+indexListe).className = "liselected";
	}
	if (indexListe==indiceMaxTitre){
		//document.getElementById("opt"+indexListe).innerHTML = "<a href='Javascript:openResultats(1)'><img src='px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats</a>";
		document.getElementById("dl11").style.display = "none";
		document.getElementById("dl12").style.display = "block";
		if (indiceMaxReal!=-1) {
			//document.getElementById("opt"+indiceMaxReal).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbRealMore+") restants";
			document.getElementById("dl21").style.display = "block";
			document.getElementById("dl22").style.display = "none";
		}
	}
	else if (indexListe==indiceMaxReal){
		//document.getElementById("opt"+indexListe).innerHTML = "<a href='Javascript:openResultats(2)'><img src='px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats</a>";
		document.getElementById("dl21").style.display = "none";
		document.getElementById("dl22").style.display = "block";
		if (indiceMaxTitre!=-1) {
			//document.getElementById("opt"+indiceMaxTitre).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbTitreMore+") restants";
			document.getElementById("dl11").style.display = "block";
			document.getElementById("dl12").style.display = "none";
		}
	}
	else {
		if (indiceMaxTitre!=-1) {
			//document.getElementById("opt"+indiceMaxTitre).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbTitreMore+") restants";
			document.getElementById("dl11").style.display = "block";
			document.getElementById("dl12").style.display = "none";
		}
		if (indiceMaxReal!=-1) {
			//document.getElementById("opt"+indiceMaxReal).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbRealMore+") restants";
			document.getElementById("dl21").style.display = "block";
			document.getElementById("dl22").style.display = "none";
		}
	}
}

function parcoursListeUp(){
	if (indexListe!=0){
		indexListe--;
		for (var j=0;j<maxItems;j++) {
		//	alert(j);
			document.getElementById("opt"+j).className = "liunselected";
		}
		if (maxItems!=0) document.getElementById("opt"+indexListe).className = "liselected";
	}
	else {
		document.getElementById("complete").style.display = "none";	
	}
	if (indexListe==indiceMaxTitre){
		//document.getElementById("opt"+indexListe).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats";
		document.getElementById("dl11").style.display = "none";
		document.getElementById("dl12").style.display = "block";
		if (indiceMaxReal!=-1){
			//document.getElementById("opt"+indiceMaxReal).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbRealMore+") restants";
			document.getElementById("dl21").style.display = "block";
			document.getElementById("dl22").style.display = "none";
		}
	}
	else if (indexListe==indiceMaxReal){
		//document.getElementById("opt"+indexListe).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;voir les r&eacute;sultats";
		document.getElementById("dl21").style.display = "none";
		document.getElementById("dl22").style.display = "block";
		if (indiceMaxTitre!=-1) {
			document.getElementById("dl11").style.display = "block";
			document.getElementById("dl12").style.display = "none";
			//document.getElementById("opt"+indiceMaxTitre).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbTitreMore+") restants";
		}
	}
	else {
		if (indiceMaxTitre!=-1) {
			//document.getElementById("opt"+indiceMaxTitre).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbTitreMore+") restants";
			document.getElementById("dl11").style.display = "block";
			document.getElementById("dl12").style.display = "none";
		}
		if (indiceMaxReal!=-1){
			//document.getElementById("opt"+indiceMaxReal).innerHTML = "<img src='px.gif' width='50px' height='12px'>&nbsp;Plus de r&eacute;sultats ("+nbRealMore+") restants";
			document.getElementById("dl21").style.display = "block";
			document.getElementById("dl22").style.display = "none";
		}
	}
} 

function parcoursListeEnter(){
//alert(indexListe+"/"+indiceMaxTitre+"/"+indiceMaxReal+"/"+(indiceMaxTitre>0)+"/"+(indexListe==indiceMaxTitre)+"/"+((indiceMaxTitre>0)&&(indexListe==indiceMaxTitre)));
	if ((indexListe>0)&&(indexListe==indiceMaxTitre)){
//alert("ben alors?");
		openResultats(0);
		return false;
	}
	else if ((indexListe>0)&&(indexListe==indiceMaxReal)){
		openResultats(20);
		return false;
	}
	else {
//alert('popoop');	
	if (indexListe!=-1){
			var html = document.getElementById("opt"+indexListe).innerHTML;
			html = html.substring(html.indexOf(";")+1).replace("+","@_@");
			document.location = "/resultats.php?m=0&s="+html;
		}
		else {
			document.location = "/resultats.php?m=4&s="+document.getElementById(chpSaisie).value;
		}
	}
}

function selectMouse(i){
	for (var j=0;j<maxItems;j++){
			document.getElementById("opt"+j).className = "liunselected";
	}
	if ((i!=indiceMaxTitre)&& (indiceMaxTitre!=-1)) {
		document.getElementById("dl11").style.display = "block";
		document.getElementById("dl12").style.display = "none";
	}
	if ((i!=indiceMaxReal)&& (indiceMaxReal!=-1)) {
		document.getElementById("dl21").style.display = "block";
		document.getElementById("dl22").style.display = "none";
	}
	document.getElementById("opt"+i).className = "liselected";
	indexListe = i;
}

function selectMouseListe(i){
	for (var j=0;j<maxItems;j++){
		document.getElementById("opt"+j).className = "liunselected";
	}
	if (i==1) indexListe = indiceMaxTitre;
	if (i==2) indexListe = indiceMaxReal;
	document.getElementById("dl"+i+"1").style.display = "none";
	document.getElementById("dl"+i+"2").style.display = "block";
}

function resetMouseListe(i){
	for (var j=0;j<maxItems;j++){
			document.getElementById("opt"+j).className = "liunselected";
	}
	document.getElementById("dl"+i+"2").style.display = "none";
	document.getElementById("dl"+i+"1").style.display = "block";
}

function isset(o) {
    return !!( typeof o != 'undefined' && o != null) ;
}

function getLeft(o) {
    if (isset(o.offsetParent)) {
		return o.offsetLeft + getLeft (o.offsetParent);
	}
	return o.offsetLeft;
}

function getTop (o) {
	if (isset(o.offsetParent)) {
        return o.offsetTop + getTop (o.offsetParent);
    }
    return o.offsetLeft;
}

function openResultats(i){
//alert(i);
		document.location ="/resultats.php?m="+i+"&s="+document.getElementById(chpSaisie).value;
		return false;
}

