
var tabIdSpan_hotel = new Array(); // contient la liste des identifiants ville pays des listes

var _xmlHttp_hotel = getHTTPObject(); //l'objet xmlHttpRequest utilisé pour contacter le serveur
var _adresseRecherche_hotel = dossier_v2+"/ajax/autocomplete_hotel_dest.php" //l'adresse à interroger pour trouver les suggestions



var _documentForm_hotel=null; // le formulaire contenant notre champ texte
var _inputField_hotel=null; // le champ texte lui-même
var _submitButton_hotel=null; // le bouton submit de notre formulaire


var _oldInputFieldValue_hotel=""; // valeur précédente du champ texte
var _currentInputFieldValue_hotel=""; // valeur actuelle du champ texte
var _resultCache_hotel=new Object(); // mécanisme de cache des requetes


var _lastKeyCode_hotel=null;
var _eventKeycode_hotel = null;

var _completeDivRows_hotel = 0;
var _completeDivDivList_hotel = null;
var _highlightedSuggestionIndex_hotel = -1;
var _highlightedSuggestionDiv_hotel = null;

// retourne un objet xmlHttpRequest.
// méthode compatible entre tous les navigateurs (IE/Firefox/Opera)



function initAutoComplete_hotel(form,field,submit){
  _documentForm_hotel=form;
  _inputField_hotel=field;
  _submitButton_hotel=submit;
 
  _inputField_hotel.autocomplete="off";
  
  creeAutocompletionDiv_hotel();
   
  _currentInputFieldValue_hotel=_inputField_hotel.value;
  _oldInputFieldValue_hotel=_currentInputFieldValue_hotel;
    
  document.onkeydown=onKeyDownHandler_hotel;
  _inputField_hotel.onkeyup=onKeyUpHandler_hotel;
  _inputField_hotel.onblur=onBlurHandler_hotel;
  window.onresize=onResizeHandler_hotel;
  
  // Premier déclenchement de la fonction dans 200 millisecondes
  tabIdSpan_hotel = new Array(); 
  setTimeout("mainLoop_hotel()",1000);
 
  
}


// tourne en permanence pour suggerer suite à un changement du champ texte
function mainLoop_hotel(){
  if(_oldInputFieldValue_hotel!=_currentInputFieldValue_hotel){
	  selec = false;
    var valeur=escapeURI_hotel(_currentInputFieldValue_hotel);
    var suggestions=_resultCache_hotel[_currentInputFieldValue_hotel];
    if(suggestions){ // la réponse était encore dans le cache
      metsEnPlace_hotel(valeur,suggestions)
    }else{
      callSuggestions_hotel(valeur) // appel distant
    }
    _inputField_hotel.focus()
  }
  _oldInputFieldValue_hotel=_currentInputFieldValue_hotel;
  setTimeout("mainLoop_hotel()",1000); // la fonction se redéclenchera dans 1000 ms
  return true
}

// echappe les caractère spéciaux
function escapeURI_hotel(La){
  if(encodeURIComponent) {
    return encodeURIComponent(La);
  }
  if(escape) {
    return escape(La)
  }
}


function callSuggestions_hotel(valeur){
	if(_xmlHttp_hotel &&_xmlHttp_hotel.readyState!=0){
		_xmlHttp_hotel.abort()
	}
 
	//appel à l'url distante
				//window.open(_adresseRecherche_hotel+"?destination="+valeur);
	_xmlHttp_hotel.open("GET",_adresseRecherche_hotel+"?destination="+valeur,true);
	_xmlHttp_hotel.onreadystatechange=function() {
	if(_xmlHttp_hotel.readyState==4&&_xmlHttp_hotel.responseXML) {
		var liste = traiteXmlSuggestions_hotel(_xmlHttp_hotel.responseXML,valeur)
			//cacheResults(valeur,liste)
			metsEnPlace_hotel(valeur,liste)
		}
	};
	// envoi de la requete
	_xmlHttp_hotel.send(null)
  
}

// Mecanisme de caching des réponses
function cacheResults_hotel(debut,suggestions){
  _resultCache_hotel[debut]=suggestions
}

// Transformation XML en tableau
function traiteXmlSuggestions_hotel(xmlDoc,valeur) {
  var options = xmlDoc.getElementsByTagName('option');
  var optionsListe = new Array();
  for (var i=0; i < options.length; ++i) {
	var txttemp = options[i].firstChild.data;
	txttemp = txttemp.toUpperCase();
	sp_txttemp = txttemp.split("||");
	txttemp = sp_txttemp[0];

	valtemp  = valeur;
	valtemp = str_replace("%20"," ",valtemp);
	valtemp =valtemp.toUpperCase();
	if(txttemp.search(valtemp)!=-1) {
		optionsListe.push(options[i].firstChild.data);
	}
  }
  return optionsListe;
}

//insère une règle avec son nom
function insereCSS_hotel(nom,regle){
  if (document.styleSheets) {
    var I=document.styleSheets[0];
    if(I.addRule){ // méthode IE
      I.addRule(nom,regle)
    }else if(I.insertRule){ // méthode DOM
      I.insertRule(nom+" { "+regle+" }",I.cssRules.length)
    }
  }
}

function initStyle_hotel(){
  var AutoCompleteDivListeStyle_hotel="font-size:11px; font-family:arial,sans-serif; word-wrap:break-word; ";
  var AutoCompleteDivStyle_hotel="display: block; padding-left: 5px; padding-right: 5px; border-bottom:1px dotted #bfbfbf; height: 15px; overflow: hidden; background-color:#f5f5f5; cursor:pointer;";
  var AutoCompleteDivActStyle_hotel="padding-left: 5px; background-color: #20badb; border-bottom:1px dotted #bfbfbf; height: 15px; color: #FFFFFF; cursor:pointer; ";
  insereCSS_hotel(".AutoCompleteDivListeStyle_hotel",AutoCompleteDivListeStyle_hotel);
  insereCSS_hotel(".AutoCompleteDiv_hotel",AutoCompleteDivStyle_hotel);
  insereCSS_hotel(".AutoCompleteDivAct_hotel",AutoCompleteDivActStyle_hotel);
}

function setStylePourElement_hotel(c,name){
  c.className=name;
}

// calcule le décalage à gauche
function calculateOffsetLeft_hotel(r){
  return calculateOffset_hotel(r,"offsetLeft")
}

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

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

// calcule la largeur du champ
function calculateWidth_hotel(){
  return _inputField_hotel.offsetWidth
}

function setCompleteDivSize_hotel(){
  if(_completeDiv_hotel){
    _completeDiv_hotel.style.left=calculateOffsetLeft_hotel(_inputField_hotel)+"px";
    _completeDiv_hotel.style.top=calculateOffsetTop_hotel(_inputField_hotel)+_inputField_hotel.offsetHeight-1+"px";
    _completeDiv_hotel.style.width=calculateWidth_hotel()+"px";
	if(15*_completeDivRows_hotel+4>200){
		_completeDiv_hotel.style.height=200+"px";
	}else{
		_completeDiv_hotel.style.height=15*(_completeDivRows_hotel+1)+4;
	}
  }
}

function creeAutocompletionDiv_hotel() {
  initStyle_hotel();
 
  _completeDiv_hotel=document.createElement("DIV");
  _completeDiv_hotel.id="completeDiv";
  var borderLeftRight=1;
  var borderTopBottom=1;
  _completeDiv_hotel.style.borderRight="#20badb "+borderLeftRight+"px solid";
  _completeDiv_hotel.style.borderLeft="#20badb "+borderLeftRight+"px solid";
  _completeDiv_hotel.style.borderTop="#20badb "+borderTopBottom+"px solid";
  _completeDiv_hotel.style.borderBottom="#20badb "+borderTopBottom+"px solid";
  _completeDiv_hotel.style.zIndex="10";
  _completeDiv_hotel.style.paddingRight="0";
  _completeDiv_hotel.style.paddingLeft="0";
  _completeDiv_hotel.style.paddingTop="0";
  _completeDiv_hotel.style.paddingBottom="0";

  setCompleteDivSize_hotel();
  
  _completeDiv_hotel.style.height="250";
  _completeDiv_hotel.style.overflow="auto";
  _completeDiv_hotel.style.overflowX="hidden";
  _completeDiv_hotel.style.overflowY="auto";
  _completeDiv_hotel.style.display="none";
  _completeDiv_hotel.style.position="absolute";
  _completeDiv_hotel.style.backgroundColor="#f5f5f5";
  _completeDiv_hotel.onmousedown=divPrincipaleOnMouseDown_hotel;
   
  document.body.appendChild(_completeDiv_hotel);
  
  setStylePourElement_hotel(_completeDiv_hotel,"AutoCompleteDivListeStyle_hotel");
  
}

function metsEnPlace_hotel(valeur, liste){
  while(_completeDiv_hotel.childNodes.length>0) {
    _completeDiv_hotel.removeChild(_completeDiv_hotel.childNodes[0]);
  }
  // mise en place des suggestions
  tabIdSpan_hotel = new Array(); 
  for(var f=0; f<liste.length; ++f){
    var nouveauDiv=document.createElement("DIV");
    nouveauDiv.onmouseup=divOnMouseUp_hotel;
    nouveauDiv.onmouseover=divOnMouseOver_hotel;
    nouveauDiv.onmouseout=divOnMouseOut_hotel;
    setStylePourElement_hotel(nouveauDiv,"AutoCompleteDiv_hotel");
    var nouveauSpan=document.createElement("SPAN");
	nouveauSpan.id = "spanSuggest" + f;
	tmp2=liste[f];
	sp_txttemp = tmp2.split("||");
	tmp2 = sp_txttemp[0];
	tabIdSpan_hotel[f] = sp_txttemp[1];
	tmp2 = tmp2.replace(valeur.toUpperCase(),"<b>" + valeur.toUpperCase() + "</b>");
	//tmp2 = tmp2.replace(valeur.toUcWords(),"<b>" + valeur.toUcWords() + "</b>");
	tmp2 = tmp2.replace(valeur,"<b>" + valeur + "</b>");
    nouveauSpan.innerHTML=tmp2; // le texte de la suggestion

	nouveauDiv.appendChild(nouveauSpan);
    _completeDiv_hotel.appendChild(nouveauDiv)
  }
  
  PressAction_hotel();
  if(_completeDivRows_hotel>0) {
    _completeDiv_hotel.height=15*_completeDivRows_hotel+4;
	
	showCompleteDiv_hotel();
	
  } else {
    hideCompleteDiv_hotel();
  }
}


// Handler pour le keydown du document
var onKeyDownHandler_hotel=function(event){
  // accès evenement compatible IE/Firefox
  if(!event&&window.event) {
    event=window.event;
  }
  // on enregistre la touche ayant déclenché l'evenement
  if(event) {
    _lastKeyCode_hotel=event.keyCode;
  }
}




// Handler pour le keyup de lu champ texte
var onKeyUpHandler_hotel=function(event){
  // accès evenement compatible IE/Firefox
  if(!event&&window.event) {
    event=window.event;
  }
  _eventKeycode_hotel=event.keyCode;
  // Dans les cas touches touche haute(38) ou touche basse (40)
  if(_eventKeycode_hotel==40||_eventKeycode_hotel==38) {
    // on autorise le blur du champ (traitement dans onblur)
    blurThenGetFocus_hotel();
  }
  // taille de la selection
  var N=rangeSize_hotel(_inputField_hotel);
  // taille du texte avant la selection (selection = suggestion d'autocomplétion)
  var v=beforeRangeSize_hotel(_inputField_hotel);
  // contenu du champ texte
  var V=_inputField_hotel.value;
  if(_eventKeycode_hotel!=0){
    if(N>0&&v!=-1) {
      // on recupere uniquement le champ texte tapé par l'utilisateur
      V=V.substring(0,v);
    }
    // 13 = touche entrée
    if(_eventKeycode_hotel==13||_eventKeycode_hotel==3){
      var d=_inputField_hotel;
      // on mets en place l'ensemble du champ texte en repoussant la selection
      if(_inputField_hotel.createTextRange){
        var t=_inputField_hotel.createTextRange();
        t.moveStart("character",_inputField_hotel.value.length);
        _inputField_hotel.select()
      } else if (d.setSelectionRange){
        _inputField_hotel.setSelectionRange(_inputField_hotel.value.length,_inputField_hotel.value.length)
      }
    } else {
      // si on a pas pu agrandir le champ non selectionné, on le mets en place violemment.
      if(_inputField_hotel.value!=V) {
			_inputField_hotel.value=V;
      }
    }
  }
  // si la touche n'est ni haut, ni bas, on stocke la valeur utilisateur du champ
  if(_eventKeycode_hotel!=40&&_eventKeycode_hotel!=38) {
    // le champ courant n est pas change si key Up ou key Down
  	_currentInputFieldValue_hotel=V;
  }
  if(handleCursorUpDownEnter_hotel(_eventKeycode_hotel)&&_eventKeycode_hotel!=0) {
    // si on a préssé une touche autre que haut/bas/enter
    PressAction_hotel();
  }
}

// Change la suggestion selectionné.
// cette méthode traite les touches haut, bas et enter
function handleCursorUpDownEnter_hotel(eventCode){
  if(eventCode==40){
    highlightNewValue_hotel(_highlightedSuggestionIndex_hotel+1);
    return false
  }else if(eventCode==38){
    highlightNewValue_hotel(_highlightedSuggestionIndex_hotel-1);
    return false
  }else if(eventCode==13||eventCode==3){
    return false
  }
  return true
}


// gère une touche pressée autre que haut/bas/enter
function PressAction_hotel(){
  _highlightedSuggestionIndex_hotel=-1;
  var suggestionList=_completeDiv_hotel.getElementsByTagName("DIV");
  var suggestionLongueur=suggestionList.length;
  // on stocke les valeurs précédentes
  // nombre de possibilités de complétion
  _completeDivRows_hotel=suggestionLongueur;
  // possiblités de complétion
  _completeDivDivList_hotel=suggestionList;
  // si le champ est vide, on cache les propositions de complétion
  if(_currentInputFieldValue_hotel==""||suggestionLongueur==0){
    hideCompleteDiv_hotel()
  }else{
    showCompleteDiv_hotel()
  }
  var trouve=false;
  // si on a du texte sur lequel travailler
  if(_currentInputFieldValue_hotel.length>0){
    var indice;
    // T vaut true si on a dans la liste de suggestions un mot commencant comme l'entrée utilisateur
    for(indice=0; indice<suggestionLongueur; indice++){
      if(getSuggestion_hotel(suggestionList.item(indice)).toUpperCase().indexOf(_currentInputFieldValue_hotel.toUpperCase())==0) {
        trouve=true;
        break
      }
    }
  }
  // on désélectionne toutes les suggestions
  for(var i=0; i<suggestionLongueur; i++) {
    setStylePourElement_hotel(suggestionList.item(i),"AutoCompleteDiv_hotel");
  }
  // si l'entrée utilisateur (n) est le début d'une suggestion (n-1) on sélectionne cette suggestion avant de continuer

  if(trouve){
    _highlightedSuggestionIndex_hotel=indice;
    _highlightedSuggestionDiv_hotel=suggestionList.item(_highlightedSuggestionIndex_hotel);
  }else{
    _highlightedSuggestionIndex_hotel=-1;
    _highlightedSuggestionDiv_hotel=null
  }
  var supprSelection=false;
  switch(_eventKeycode_hotel){
    // cursor left, cursor right, page up, page down, others??
    case 8:
    case 33:
    case 34:
    case 35:
    case 35:
    case 36:
    case 37:
    case 39:
    case 45:
    case 46:
      // on supprime la suggestion du texte utilisateur
      supprSelection=true;
      break;
    default:
      break
  }
  // si on a une suggestion (n-1) sélectionnée
  if(!supprSelection&&_highlightedSuggestionDiv_hotel){
    setStylePourElement_hotel(_highlightedSuggestionDiv_hotel,"AutoCompleteDivAct_hotel");
    var z;
    if(trouve) {
      z=getSuggestion_hotel(_highlightedSuggestionDiv_hotel).substr(0);
    } else {
      z=_currentInputFieldValue_hotel;
    }

    if(z!=_inputField_hotel.value){
			
			
      if(_inputField_hotel.value!=_currentInputFieldValue_hotel) {
        return;
      }
      // si on peut créer des range dans le document
      if(_inputField_hotel.createTextRange||_inputField_hotel.setSelectionRange) {
		
		// modification du 12/03/2010
		
		//_inputField_hotel.value=z;
		
		 _inputField_hotel.value=getSuggestion_hotel(_highlightedSuggestionDiv_hotel);
 		updt_id_destination_hotel(getSuggestionId_hotel(_highlightedSuggestionDiv_hotel));
      }
      // on sélectionne la fin de la suggestion
      if(_inputField_hotel.createTextRange){
        var t=_inputField_hotel.createTextRange();
        t.moveStart("character",_currentInputFieldValue_hotel.length);
        t.select()
      }else if(_inputField_hotel.setSelectionRange){
        _inputField_hotel.setSelectionRange(_currentInputFieldValue_hotel.length,_inputField_hotel.value.length)
      }
    }
  }else{
    // sinon, plus aucune suggestion de sélectionnée
    _highlightedSuggestionIndex_hotel=-1;
  }
}

var _cursorUpDownPressed_hotel = null;

// permet le blur du champ texte après que la touche haut/bas ai été pressé.
// le focus est récupéré après traitement (via le timeout).
function blurThenGetFocus_hotel(){
  _cursorUpDownPressed_hotel=true;
  _inputField_hotel.blur();
  setTimeout("_inputField_hotel.focus();",10);
  return
}

// taille de la selection dans le champ input
function rangeSize_hotel(n){
  var N=-1;
  if(n.createTextRange){
    var fa=document.selection.createRange().duplicate();
    N=fa.text.length
  }else if(n.setSelectionRange){
    N=n.selectionEnd-n.selectionStart
  }
  return N
}

// taille du champ input non selectionne
function beforeRangeSize_hotel(n){
  var v=0;
  if(n.createTextRange){
    var fa=document.selection.createRange().duplicate();
    fa.moveEnd("textedit",1);
    v=n.value.length-fa.text.length
  }else if(n.setSelectionRange){
    v=n.selectionStart
  }else{
    v=-1
  }
  return v
}

// Place le curseur à la fin du champ
function cursorAfterValue_hotel(n){
  if(n.createTextRange){
    var t=n.createTextRange();
    t.moveStart("character",n.value.length);
    t.select()
  } else if(n.setSelectionRange) {
    n.setSelectionRange(n.value.length,n.value.length)
  }
}


// Retourne la valeur de la possibilite (texte) contenu dans une div de possibilite
function getSuggestion_hotel(uneDiv){
	if(!uneDiv) {
		return null;
	}

	V1 = trimCR_hotel(uneDiv.getElementsByTagName('span')[0].innerHTML);
	id_temp = uneDiv.getElementsByTagName('span')[0].id;
	id_temp = str_replace("spanSuggest","",id_temp);
	id_temp = parseInt(id_temp);
	
	V2 = str_replace("<B>","",V1);
	V3 = str_replace("<b>","",V2);
	V4 = str_replace("</B>","",V3);
	V5 = str_replace("</b>","",V4);
	return V5;
  
}
function getSuggestionId_hotel(uneDiv){
	if(!uneDiv) {
		return null;
	}

	V1 = trimCR_hotel(uneDiv.getElementsByTagName('span')[0].innerHTML);
	id_temp = uneDiv.getElementsByTagName('span')[0].id;
	id_temp = str_replace("spanSuggest","",id_temp);
	id_temp = parseInt(id_temp);
	return tabIdSpan_hotel[id_temp];
}

// supprime les caractères retour chariot et line feed d'une chaine de caractères
function trimCR_hotel(chaine){
  for(var f=0,nChaine="",zb="\n\r"; f<chaine.length; f++) {
    if (zb.indexOf(chaine.charAt(f))==-1) {
      nChaine+=chaine.charAt(f);
    }
  }
  return nChaine
}

// Cache completement les choix de completion
function hideCompleteDiv_hotel(){
  	_completeDiv_hotel.style.display="none";
}

// Rends les choix de completion visibles
function showCompleteDiv_hotel(){
  _completeDiv_hotel.style.display="inline";
  setCompleteDivSize_hotel()
}

// Change la suggestion en surbrillance
function highlightNewValue_hotel(C){

  if(!_completeDivDivList_hotel||_completeDivRows_hotel<=0) {
    return;
  }
  showCompleteDiv_hotel();
  if(C>=_completeDivRows_hotel){
    C=_completeDivRows_hotel-1
  }
  if(_highlightedSuggestionIndex_hotel!=-1&&C!=_highlightedSuggestionIndex_hotel){
    setStylePourElement_hotel(_highlightedSuggestionDiv_hotel,"AutoCompleteDiv_hotel");
    _highlightedSuggestionIndex_hotel=-1
  }

  if(C<0){
    _highlightedSuggestionIndex_hotel=-1;
    _inputField_hotel.focus();
    return
  }
  
  _highlightedSuggestionIndex_hotel=C;
  _highlightedSuggestionDiv_hotel=_completeDivDivList_hotel.item(C);
  setStylePourElement_hotel(_highlightedSuggestionDiv_hotel,"AutoCompleteDivAct_hotel");

}

// Handler de resize de la fenetre
var onResizeHandler_hotel=function(event){
  // recalcule la taille des suggestions
  setCompleteDivSize_hotel();
}

// Handler de blur sur le champ texte
var onBlurHandler_hotel=function(event){
  
  if(!_cursorUpDownPressed_hotel){
    // si le blur n'est pas causé par la touche haut/bas
    hideCompleteDiv_hotel();
    // Si la dernière touche préssé est tab, on passe au bouton de validation
    if(_lastKeyCode_hotel==9){
      _lastKeyCode_hotel=-1
    }
  }
  _cursorUpDownPressed_hotel=false
};

// declenchee quand on clique sur une div contenant une possibilite
var divOnMouseUp_hotel=function(){
	
	_inputField_hotel.value=getSuggestion_hotel(this);
	updt_id_destination_hotel(getSuggestionId_hotel(this));
	hideCompleteDiv_hotel();
	_cursorUpDownPressed_hotel=false;
	setTimeout("_inputField_hotel.focus();",10);
};

// declenchee quand on passe sur une div de possibilite. La div précédente est passee en style normal
var divOnMouseOver_hotel=function(){
  if(_highlightedSuggestionDiv_hotel) {
    setStylePourElement_hotel(_highlightedSuggestionDiv_hotel,"AutoCompleteDiv_hotel");
  }
  setStylePourElement_hotel(this,"AutoCompleteDivAct_hotel")
};

// declenchee quand la sourie quitte une div de possiblite. La div repasse a l'etat normal
var divOnMouseOut_hotel = function(){
  setStylePourElement_hotel(this,"AutoCompleteDiv_hotel");
};

var divPrincipaleOnScroll_hotel = function() {
	//_cursorUpDownPressed=true;
}

var divPrincipaleOnMouseDown_hotel = function() {
	_cursorUpDownPressed_hotel=true;
}