// Compatibilite Firefox : 17 mars 07 
// Utilisation de la carte pour selectionner rechercher les trajets : November 2008 (PDb)

// retourne un objet xmlHttpRequest.
// méthode compatible entre tous les navigateurs (IE/Firefox/Opera)

// Septembre 2009 : gestion du telechargement complet de la carte google afin de donner la main a l utilisateur

var map;
var pointCenter;
var geocoder;
var address;
var latDefault;
var lonDefault;
var journey;
var _adresseSelectCity = "ajaxEngineSelectCityFromMap.php" //l'adresse à interroger pour trouver le geoid de la ville selectionnee sur la map google
var _ClickEventListener;
var marker;
var divInfoJourney;
var getSelectedCity = new Array();
var timer;
var polySearchZone;
var radius = 8;
var markerSelectCity;
var markerSelectPoly;
var affi;
var markerAir;
var mapId;
var distance;
var markerSpe;
var time_mainLopp = 600;
var markerListCities = new Array();
var polyline = new Array();
var lenTabC;
var pCenter;
var zoneWithCities;
var _oldInputFieldValue= new Array(); // valeur précédente du champ texte
var _currentInputFieldValue= new Array(); // valeur actuelle du champ texte
var _resultCache=new Object(); // mécanisme de cache des requetes
var _currentField = ''; // indique le nom du champ texte ou se deroule l autocompletion
var aC = 0;
var _xmlHttp = null; //l'objet xmlHttpRequest utilisé pour contacter le serveur
var _adresseRecherche = "/elt/ajaxEngine.php" //l'adresse à interroger pour trouver les suggestions
var _eventKeycode = null;
var _completeDivRows = new Array(); // avant initialise a 0
var _completeDivDivList = new Array(); // avant null
var _highlightedSuggestionIndex = new Array(); // avant -1
var _highlightedSuggestionDiv = new Array(); // avant null
var _cursorUpDownPressed = null;
var _journey;
var newMarkers = new Array();
var latLngs = new Array();
var icons = new Array();

function displayEmailBox(to,trajet,date_trajet,from,root_web,nameMemberToContact,nameMemberRequesting,typeTrajet,id_trajet,id_compte_requesting,id_compte_to_contact,ori,nom_sitepartenaire) {
	// Permet un membre interesse par une annonces
	// d envoyer un email a l autre membre pour signaler son interet et 
	// demander si l offre est toujours valable
	var request = GXmlHttp.create();
  var liste;
  adresseAppel = "send_email_contact_member.php";
  textContact = '';
  mail_mailing = '';
  memberToContact = nameMemberToContact.substring(0, 1).toUpperCase() + nameMemberToContact.substring(1, nameMemberToContact.length).toLowerCase();
  memberRequesting = nameMemberRequesting.substring(0, 1).toUpperCase() + nameMemberRequesting.substring(1, nameMemberRequesting.length).toLowerCase();
  titleEmailHTML = trajet + '<br>' + date_trajet;
  sujet = 'Proposition de Covoiturage par '+nameMemberRequesting.substring(0,1).toUpperCase()+nameMemberRequesting.substring(1);
  if (nom_sitepartenaire == 'adia') {
    sujet += ' (membre CoVoiturage.com-Adia) !';
  } else {
    sujet += ' (membre CoVoiturage.com) !';
  }
	paramAppel = 'to=' + to + '&from=' + from + '&text_confirmation_email=' + textContact + '&titleEmailHTML=' + titleEmailHTML;
	paramAppel = paramAppel + '&sujet='+sujet+'&typeTrajet='+typeTrajet+'&id_compte_to_contact='+id_compte_to_contact;
 	paramAppel = paramAppel + '&root_web='+root_web+'&mail_mailing='+mail_mailing+'&memberToContact='+memberToContact;
 	paramAppel = paramAppel + '&id_trajet='+id_trajet+'&id_compte_requesting='+id_compte_requesting+'&memberRequesting='+memberRequesting;
	paramAppel = paramAppel + '&ori=' + ori;
	adresseAppel = adresseAppel + '?' + paramAppel;
  request.open("GET", adresseAppel, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var envoiOk = request.responseText;
      document.getElementById('sendEmail').innerHTML = envoiOk;
    }
  }
  request.send(null);
	
}

function load(lat,lon) {
      if (GBrowserIsCompatible()) {
        // var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(lat, lon), 10);
   }
}

function addSelectMarker() {
  icon = new GIcon();
  if (document.getElementById('lang').value == 'FR') {
    icon.image = "http://www.covoiturage.com/img/centerArrow.jpg";
  }
  if (document.getElementById('lang').value == 'UK') {
    icon.image = "http://www.car-pooling.com/img/centerArrow.jpg";
  }
  // icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
  icon.iconSize = new GSize(20, 25);
  icon.iconAnchor = new GPoint(10, 25);
  icon.infoWindowAnchor = new GPoint(10,5);
  gicon = new GIcon(icon);
  gicon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
  gicon.iconAnchor = new GPoint(-20, 20);

  if (document.getElementById('lang').value == 'FR') {
    markerSelectPolyOptions = {icon:icon, draggable: true, bouncy : false, title: "deplacer le curseur pour zoomer sur une autre region"};
  }
  if (document.getElementById('lang').value == 'UK') {
    markerSelectPolyOptions = {icon:icon, draggable: true, bouncy : false, title: "move the cursor on the area you want to zoom on"};
  }
  markerSelectCity = new GMarker(map.getCenter(), markerSelectPolyOptions);
  map.addOverlay(markerSelectCity);
  infoWindow();
  
  GEvent.addListener(markerSelectCity, "dragstart", function (latlng) {
    affi.style.visibility = 'hidden';
	map.closeInfoWindow();
	if (!(polySearchZone == undefined)) {
	  map.removeOverlay(polySearchZone);
	}
	citySearchFromMap = 0;
  });
  GEvent.addListener(markerSelectCity, "dragend", function (latlng) {
    citySearchFromMap = 1;
    validateCity(latlng.lat(),latlng.lng());
  });
}

function resizeMap(newWidth) {
		mapId.style.width = newWidth + 'px';
    map.checkResize(); 
}

function initializeMAP(nameMap) {
  map = new GMap2(document.getElementById(nameMap.id));
  pointCenter = new GLatLng(latDefault, lonDefault);
  map.setCenter(pointCenter, 10);
    
  map.addControl(new GSmallZoomControl);
  map.addControl(new GScaleControl());
  map.addControl(new GMenuMapTypeControl());
  _checkEndLoadingListener = GEvent.addListener(map, "tilesloaded", endLoading);
  if (document.getElementById('seeCursor').value == 'y') {
    addSelectMarker();
  }
  // map.addControl(new GLargeMapControl);
  // _ClickEventListener = GEvent.addListener(map, "click", getAddress);
  // affichage du marker pour selectionner les villes avec l info bulle indiquant comment l utiliser
  if (!(document.getElementById('box') == undefined)) {
  // createSelectionMarker(pointCenter);
  // infoWindow();
    _ZoomEventListener = GEvent.addListener(map, "zoomend", moveCursor);
    _DragEventListener = GEvent.addListener(map, "dragend", moveCursor);
	  _CloseInfoWindowEventListener = GEvent.addListener(map, "infowindowclose", unBlockReload);
    geocoder = new GClientGeocoder();
  }     
}

function waitUntilLoad() {
  if (!(_documentForm == undefined || map==undefined)) {
		showJourney();
		clearTimeout(timer);
	
		if (!(document.getElementById('autoSearch') == undefined) ) {
		  if (document.getElementById('autoSearch').value == 1) {
		     displayJourneysOnMap();
		  }
		}
  } 
}

function endLoading() {
	timer = setTimeout("waitUntilLoad()",50)
	layerOnLoad = document.getElementById('WaitOnLoad');
  layerOnLoad.style.visibility = 'hidden';
  layerOnLoad.style.zIndex = 9;
  layerOnLoad.style.width = '0px';
  layerOnLoad.style.height = '0px';
  GEvent.removeListener(_checkEndLoadingListener);  
}

function showLoading() {
  layerOnLoad = document.getElementById('WaitOnLoad');
  layerOnLoad.style.width = '450px';
  layerOnLoad.style.height = '450px';
	layerOnLoad.style.visibility = 'visible';
  layerOnLoad.style.left = '600px';
  layerOnLoad.style.top = '300px';
	layerOnLoad.style.zIndex = '1';
	layerOnLoad.innerHTML = 'Loading map...';
}

function unBlockReload() {
  map.enableDoubleClickZoom();
  map.enableDragging();	
}

function infoWindow() {
  if (document.getElementById('lang').value == 'UK') {
		textWindow = 'Please drag the marker to the place<br>you want to select or type in the name of the place';
  	textWindow = textWindow + '<br><br>Click here not to show this message again ';
  }
	if (document.getElementById('lang').value == 'FR') {
		textWindow = 'Positionner le curseur sur le lieu<br>que vous souhaitez s&eacute;lectionner<br>ou renseigner directement<br> le nom de la ville';
  	textWindow = textWindow + '<br><br>Cliquer ici pour ne plus faire<br>apparaitre ce message ';
  }
  if (document.getElementById('deptS').value == '') {
    // map.addOverlay(marker);
	if (document.getElementById('showWindow').value == 1) {
      textWindow = textWindow + '<input type=checkbox name=showWindow id=showWindow ';
	  textWindow = textWindow + 'onClick="javascript:setShow = eval(document.getElementById(showWindow)); setShow.value';
	  textWindow = textWindow + ' = 0; map.closeInfoWindow();">';
	  if (document.getElementById('sitepartenaire').value != '') {
	    markerSelectCity.openInfoWindowHtml(textWindow,{maxWidth : '200'});
	  }
	}
  }
}

// Gestion du marker lors des changements de la carte
// moveend()
// zoomend(oldLevel:Number, newLevel:Number)

function moveCursor() {
  // move the draggable cursor to the center of the map
  // display at the center of the map the marker to select a new city
  // unless box is displayed
  if (!(document.getElementById('box') == undefined)) { 
    if (document.getElementById('box').style.visibility != 'visible') {
      if( ! (markerSelectCity == undefined)) {  // newCenter = map.getCenter();
        // createSelectionMarker(newCenter);
	      markerSelectCity.setLatLng(map.getCenter());
        infoWindow();
      }
    }
  }
}

function getAddress(overlay, latlng) {
  if (latlng != null) {
    address = latlng;
	// GEvent.removeListener(_ClickEventListener);
    geocoder.getLocations(latlng, showAddress);
  }
}

function handleErrors(codeErr){
  if (codeErr == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
  else if (codeErr == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.");
  else if (codeErr == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.");
  else if (codeErr == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given.");
  else if (codeErr == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.");
  else alert("An unknown error occurred.");
}

function showAddress(response) {
  var paramSelectedCity;
  // map.clearOverlays();
  if (!response || response.Status.code != 200) {
    handleErrors(response.Status.code);
	// display again the cursor
	moveCursor();  
  } else {
    place = response.Placemark[0];
    lati = place.Point.coordinates[1];
	longi = place.Point.coordinates[0];
	validateCity(lati,longi);
  }
}

function selectCity(listeInfoCity,index) {
   var details = new Array();
   // fill in the different fields to identify the City and to prepare for the search
   // like geoname id, lat, lon, etc.
   map.removeOverlay(polySearchZone);
   map.closeInfoWindow();
   
   allInfo = listeInfoCity[0].split('/SEPA/');
   
   iconToShow = allInfo[5]; 
   
   longi = allInfo[4];
   lati = allInfo[3];
   country = allInfo[2];
   codeCity = allInfo[1];   
   city = allInfo[0].replace('SIGNAPO','\'');;
   cityComplet = city + ' - ' + getNameCountry(country);

   _currentInputFieldValue[index] = cityComplet;
   _oldInputFieldValue[index] = cityComplet;
   storeCodeVille = document.getElementById("codeVille_" + _inputFieldName[index]);
   storeCodeVille.value = codeCity;
   storeNameOnly = document.getElementById("nameOnly_" + _inputFieldName[index]);
   storeNameOnly.value = city;
   storeNomVilleComplet = document.getElementById("nomVilleComplet_" + _inputFieldName[index] );
   storeNomVilleComplet.value = cityComplet;
   storeNomVille = document.getElementById("" + _inputFieldName[index]);
   storeNomVille.value = cityComplet;
   storeLon = document.getElementById("lon_" + _inputFieldName[index]);
   storeLon.value = longi;
   storeLat = document.getElementById("lat_" + _inputFieldName[index]);
   storeLat.value = lati;
   storeCodePays = document.getElementById("code_pays_" + _inputFieldName[index]);
   storeCodePays.value = country;
   storeStyle = document.getElementById(""+ _inputFieldName[index]);
   storeStyle.style.borderColor = '#ffb211';
   storeIcon = document.getElementById("imageIcon_" + _inputFieldName[index]);
   storeIcon.value = iconToShow;
   affi.style.visibility = 'hidden';	
   // pressAction(9);
   // showJourney();
}

function validateCity(lati,longi) {
  // Create a match between our database and the georequest from google
  // we need to get the geonameid of the location
  // we need to remove any potential marker displayed for locating places with similar names
  map.removeOverlay(markerListCities);
  var request = GXmlHttp.create();
  var liste;
  var tabC = new Array();
  adresseAppel = _adresseSelectCity+'?lat='+lati+'&lon='+longi+'&radius='+radius;
  request.open("GET", adresseAppel, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var liste = request.responseText;
	  liste = liste.replace('%26','&');
	  tabC = liste.split('/SEPA/');
	  // on affiche une selection de lieux que le covoitureur doit choisir
	  // message = 'Multiple places located. Please choose:<br><br>';
	  message = 'S&eacute;lectionnez une des localit&eacute;s dans la liste suivante :<br><br>';
	  maxLat = tabC[1];
	  minLat = tabC[3];
	  maxLon = tabC[2];
	  minLon = tabC[4];
	  for(var f=1; f<=(tabC.length)/6; f++){
		details = tabC[6*f]+'/SEPA/'+tabC[6*f+1]+'/SEPA/'+tabC[6*f+2]+'/SEPA/'+tabC[6*f+3]+'/SEPA/'+tabC[6*f+4]+'/SEPA/'+tabC[6*f+5];	
		// message = message + '<a href="javascript:eval(\'this.document.getElementById(''valid.click;\');">'+displayText[0]+'</a><br>';
		message += '<a onmouseout="map.removeOverlay(markerListCities);" onmouseover="showJustCity';
		message += '([\''+escapeURI(details)+'\']);" ';
		message += 'href="javascript:displayCity';
		message += '([\''+escapeURI(details)+'\']);">'+tabC[6*f]+'</a><br>';
		if ( tabC[6*f+5] != 'NOLOGO') {
		  markerSpe = addIconSpe(tabC[6*f+5],tabC[6*f],tabC[6*f+3],tabC[6*f+4]);
		}
		}
	  message += '<br><a href="javascript:closeBox();">Fermer</a>';
	  height = 12*(22+2);
	  affi.style.height = height + 'px';
	  if (document.getElementById('sitepartenaire').value != '') {
			affi.style.left = (mapId.offsetLeft - 185 - 5) + 'px';
	  } else {
	  	affi.style.left = (mapId.offsetLeft + mapId.offsetWidth - 5) + 'px';
  	}
	  affi.style.top = mapId.offsetTop + 'px';
	  
	  // while box is on it is not possible to click on the map as it causes errors
	  map.disableDoubleClickZoom();
      map.disableDragging();
	  // GEvent.removeListener(_ClickEventListener);
	  affi.style.visibility = 'visible';
	  affi.innerHTML = message;
	  // alert(message);
	  drawPolySearch(lati,longi);
	  ne = new GLatLng(minLat,maxLon);
	  sw= new GLatLng(maxLat,minLon);
	  zoneWithCities = new GLatLngBounds(sw, ne);
	  if (map.getBoundsZoomLevel(zoneWithCities) == 1) {;
		// alert(map.getZoom());
		zoneWithCities = new GLatLngBounds(ne, sw);
	  }
	  map.setZoom(map.getBoundsZoomLevel(zoneWithCities));
	  map.setCenter(new GLatLng(lati,longi),10);
	  markerSelectCity.setLatLng(new GLatLng(lati,longi));
	}
  }
  request.send(null);
}

function addIconSpe(imageIcon, titleIcon,latIcon,lonIcon) {
	var iconSpe = new GIcon();
	iconSpe.image = imageIcon;
  	iconSpe.iconSize = new GSize(20, 20);
  	iconSpe.iconAnchor = new GPoint(6, 20);
		  
	markerSpePoint = new GLatLng(latIcon,lonIcon);
	markerSpeOptions = { icon:iconSpe, title : titleIcon };
	var nameMarker = new GMarker(markerSpePoint, markerSpeOptions);
	map.addOverlay(nameMarker);
	GEvent.addListener(nameMarker, "click", function() {
	  // this.openInfoWindow(titleIcon);
	});
	return nameMarker; 
}

function drawPolySearch(latiCenter,longiCenter) {
  var d2r = Math.PI/180 ;                // degrees to radians
  var r2d = 180/Math.PI ;                // radians to degrees
  var Clat = (radius/3963) * r2d ;      //  using 3963 as earth's radius
  var Clng = Clat/Math.cos(latiCenter*d2r);

  var tabP = new Array();
  for (var h=0; h<360; h++) {
    Cx = longiCenter + (Clng * Math.cos(h/360*2*Math.PI));
    Cy = latiCenter + (Clat * Math.sin(h/360*2*Math.PI));
    tabP[h] = new GLatLng(Cy,Cx);	
  }
  polySearchZone = new GPolygon(tabP, "#ff0000",2,1,{fillColor:"#aa1100", fillOpacity:0.15});
  map.addOverlay(polySearchZone);
}

function closeBox() {
  // _ClickEventListener = GEvent.addListener(map, "click", getAddress);
  map.removeOverlay(polySearchZone);
  if (markerAir) {
    map.removeOverlay(markerAir);
  }
  document.getElementById("box").style.visibility= 'hidden'; 
  moveCursor();
  map.enableDoubleClickZoom();
  map.enableDragging();	
}

function showJustCity(data) {
  // display only the marker and not the infoWindow to be able to distinguish between locations with similar names
  // but different places
  dataCity = data[0].split('%2F');
  pointCity = new GLatLng(dataCity[3],dataCity[4]);
  // remove the marker previously highlighted
  if (!(markerListCities == undefined)) {
    map.removeOverlay(markerListCities);
  }
  // markerListCities = new GMarker(pointCity);
  // map.addOverlay(markerListCities);
  markerSelectCity.setLatLng(pointCity);
}

function displayCity(param) {
  var shortTextCity = new Array();
  map.disableDoubleClickZoom();
  map.disableDragging();
  if (document.getElementById('lang').value == 'FR') {
    shortTextCity[0] = "Depuis";
    shortTextCity[1] = "Vers";
    shortTextCity[2] = "Etape 1";
    shortTextCity[3] = "Etape 2";
    shortTextCity[4] = "Etape 3";
  }
  if (document.getElementById('lang').value == 'UK') {
    shortTextCity[0] = "From";
    shortTextCity[1] = "To";
    shortTextCity[2] = "Via 1";
    shortTextCity[3] = "Via 2";
    shortTextCity[4] = "Via 3";
  }
  document.getElementById("box").style.visibility = 'hidden'
  paramSelectedCity = param[0].split('/SEPA/');
  map.removeOverlay(polySearchZone);
  // affichage du marker
  point = new GLatLng(paramSelectedCity[3],paramSelectedCity[4]);
  param[0] = param[0].replace('&#39;','SIGNAPO');
  var message = '';
  for (var k=0;k<_inputFieldName.length;k++) {
  /*
  message = message + '<b><a onmouseout="javascript:parent.document.getElementById('''+_inputFieldName[k]+'.style.borderColor=\'#ffb211\'";';
	message += ' onmouseover="javascript:parent.document.getElementById(''';
	message += _inputFieldName[k]+'.style.borderColor=\'green\';"';
	message += 'href="javascript:parent.document.getElementById('''+_inputFieldName[k]+'.style.borderColor=\'white\'; ';
	message += 'parent.selectCity([\''+param[0]+'\'],'+k+'); ">'+shortTextCity[k]+'</a> ';
	*/
  message = message + '<b><a onmouseout="javascript:document.getElementById(\''+_inputFieldName[k]+'\').style.borderColor=\'#ffb211\'";';
	message += ' onmouseover="javascript:document.getElementById(\'';
	message += _inputFieldName[k]+'\').style.borderColor=\'green\';"';
	message += 'href="javascript:document.getElementById(\''+_inputFieldName[k]+'\').style.borderColor=\'white\'; ';
	message += 'selectCity([\''+param[0]+'\'],'+k+'); ">'+shortTextCity[k]+'</a> ';
  }
  map.setCenter(point,10);
  markerSelectCity.setLatLng(point);	
  if (document.getElementById('lang').value == 'UK') {
    markerSelectCity.openInfoWindowHtml(message + '<br/><b>Name City: </b>' + paramSelectedCity[0] + '<br/>' + '<b>Country:</b> ' + getNameCountry+(paramSelectedCity[2]));
  }
  if (document.getElementById('lang').value == 'FR') {
    markerSelectCity.openInfoWindowHtml(message + '<br/><b>Nom de la localit&eacute; : </b>' + paramSelectedCity[0] + '<br/>' + '<b>Pays :</b> ' + getNameCountry(paramSelectedCity[2]));
  }
  ll = 1;
}

function createSelectionMarker(point) {
  var iconMainMarker = new GIcon();
  // icon.image = "http://www.car-pooling.com/img/centerArrow.jpg";
  iconMainMarker.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
  iconMainMarker.iconSize = new GSize(20, 20);
  iconMainMarker.iconAnchor = new GPoint(6, 20);
  marker = new GMarker(point, {bouncy: false, draggable: true, title: 'Please drag me to the next city you want to select or type in the name of the place'});
  GEvent.addListener(marker, "dragstart", function() {
    map.closeInfoWindow();
  });
  GEvent.addListener(marker, "dragend", function () {
     var pt = marker.getPoint();
	 map.panTo(pt);
	 geocoder.getLocations(new GLatLng(pt.lat(), pt.lng()), showAddress);
	 map.removeOverlay(marker);
  });	 
}

function displayJourneysOnMap() {
  // Display on the Map all the journeys and the corresponding list in a div 
  // below the Map_adresseGetLatLng = "ajaxGetLatLng.php";
  _adresseGetListJ = "http://www.covoiturage.com/elt/ajaxGetListJourneys.php";
  var request = GXmlHttp.create();
  var requestLatLng = GXmlHttp.create();
  var liste;
  dateD = document.getElementById('date_depart').value;
  codeVilleD = document.getElementById("codeVille_"+_inputFieldName[0]).value;
  codeVilleA = document.getElementById("codeVille_"+_inputFieldName[1]).value;
  distVilleD = document.getElementById('dist_dep').value;
  distVilleA = document.getElementById('dist_arr').value;
  flexiDate = document.getElementById('plage_jours').value;
  codePostalDep = document.getElementById('codeP_dep').value
  codePostalArr = document.getElementById('codeP_arr').value
  session_id = document.getElementById('idSession').value;
  id_group = document.getElementById('id_group').value;
  adresseAppel = _adresseGetListJ+'?session_id='+session_id+'&id_group='+id_group+'&codeP_dep='+codePostalDep+'&codeP_arr='+codePostalArr+'&plage_jours='+flexiDate+'&dist_dep='+distVilleD+'&dist_arr='+distVilleA+'&date_depart='+dateD+'&codeVille_ville_depart='+codeVilleD+'&codeVille_ville_arrivee='+codeVilleA;
  request.open("GET", adresseAppel, true);
  document.getElementById('listJourneys').innerHTML = '<p align=center class=titre>Veuillez patientez pendant le chargement des r&eacute;sultats de la recherche. Merci</p>';
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var liste = request.responseText;
	    map.clearOverlays();
	    if (liste.indexOf('aucun trajet') == -1) {
	    polyline = [];
	    position = liste.indexOf('/SEPA//');
	    coord = liste.substr(0,position);
		  coord = 'debut/SEPA/debut/SEPA/' + coord;
	    tabC = coord.split('/SEPA/');
	    ne = new GLatLng(tabC[2],tabC[4]);
	    sw = new GLatLng(tabC[3],tabC[5]);
	    pCenter = new GLatLng((eval(tabC[2])+eval(tabC[3]))/2,(eval(tabC[4])+eval(tabC[5]))/2);
	    zoneWithCities = new GLatLngBounds(sw, ne);
	    liste = liste.substr(position+12);
		  showJourney();
		  lenTabC = tabC.length;
	    for (var k=1; k<((tabC.length)/6); k++) {
	      point1 = new GLatLng(tabC[k*6],tabC[k*6+1]);
		    point2 = new GLatLng(tabC[k*6+2],tabC[k*6+3]);
		    polyline[k-1] = new GPolyline( [ point1 , point2 ], "#ff0000", 2,1);
		    map.addOverlay(polyline[k-1]);  
		    GEvent.addListener(polyline[k-1], "click", function(latlng) {
            indexP = -1;
			      PolyClick_x1 = eval(this.getVertex(0).x);
			      PolyClick_y1 = eval(this.getVertex(0).y);
			      PolyClick_x2 = eval(this.getVertex(1).x);
						PolyClick_y2 = eval(this.getVertex(1).y);
						var findJ = new Array();
						text = '';  
						for (var v=1; v<((tabC.length)/6); v++) {
						  Poly_x1 = eval(polyline[v-1].getVertex(0).x);
				  		Poly_y1 = eval(polyline[v-1].getVertex(0).y);
				  		Poly_x2 = eval(polyline[v-1].getVertex(1).x);
						  Poly_y2 = eval(polyline[v-1].getVertex(1).y);
						  if ( (Poly_x1 == PolyClick_x1) && (Poly_x2 == PolyClick_x2) && (Poly_y1 == PolyClick_y1) && (Poly_y2 == PolyClick_y2)) {
						    indexP++;
							  findJ[indexP] = v;
							  lien = tabC[v*6+5];
							  last = '<a '+ lien + tabC[v*6+4] + '</a><br>';
							  text += last;
              }   
						}	
						if (document.getElementById('lang').value == 'FR') {
			  			text = '<b>'+(indexP+1)+' Trajet(s)</b><br><br>' + text;
						}	
						if (document.getElementById('lang').value == 'UK') {
						  text = '<b>'+(indexP+1)+' Journey(s)</b><br><br>' + text;
						}
						if (!(markerSelectPoly == undefined)) {
						  map.removeOverlay(markerSelectPoly);
						}
			
						// Create a carPool marker icon
            var carPool = new GIcon(G_DEFAULT_ICON);
            if (document.getElementById('lang').value == 'FR') {
					  carPool.image = "http://www.covoiturage.com/img/logo.jpg";
						}
						if (document.getElementById('lang').value == 'UK') {
			  			carPool.image = "http://www.car-pooling.com/img/covoiturage.gif";
						}			
            carPool.iconSize = new GSize(60, 40);
						carPool.iconAnchor = new GPoint(30, 20);
						carPool.infoWindowAnchor = new GPoint(30, 1);
			
            // Set up our GMarkerOptions object
            markerOptions = { icon:carPool };
						markerSelectPoly = new GMarker(latlng, markerOptions);
            map.addOverlay(markerSelectPoly);
						markerSelectPoly.openInfoWindowHtml(text);
						GEvent.addListener(markerSelectPoly,"infowindowbeforeclose", function() {
				  		map.setCenter(pCenter,10);
	  	  			map.setZoom(map.getBoundsZoomLevel(zoneWithCities));
		  		  	map.removeOverlay(markerSelectPoly);
						}); 
      }); // End Listener click on polyline
		  
	  } // End boucle affichage de tous les trajets sur la carte
   	map.setCenter(pCenter,10);
	  map.setZoom(map.getBoundsZoomLevel(zoneWithCities));
	  } else {
	    liste = liste.substr(1,liste.length);
	    showJourney();
	  }
	  document.getElementById('listJourneys').style.visibility = 'visible';
	  document.getElementById('listJourneys').innerHTML = liste;  
	}  // End commande Ajax a fonctinne
  } // End appel Ajax pour recuperer la liste des trajets
  request.send(null);
}

function getEncoded(p1,p2) {
  chaineEncoded = "{uxhH{{eM_t~A_deI";
  return chaineEncoded;
}

function infoLine() {
  alert('c est un trajet');
}

var newPoly;

function highlightPolyline(f) {
  polyline[f].setStrokeStyle({color:"#00ffff"});
}

function hidePolyline(f) {
  polyline[f].setStrokeStyle({color:"#ff0000"});
}

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é par le navigateur
    alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
  }
  return xhr;
}

var _documentForm=null; // le formulaire contenant notre champ texte
var _inputFieldName= new Array(); // le champ texte lui-même
var _submitButton=null; // le bouton submit de notre formulaire

function isset(variable)
{
    return (typeof(variable) != 'undefined');
}

// Fonction init pour le formulaire et le bouton submit
function initAutoComplete(form,submit,lat,lon,nameMap,nameInfoJourney,villes){
  _documentForm=form;
  _documentForm.autocomplete="off";
  initAutoCompleteVilles(villes);
  latDefault = lat;
  lonDefault = lon;
  affi = document.getElementById("box");
  mapId = document.getElementById(nameMap.id);
  // the div to display the directions of the journey
  divInfoJourney = nameInfoJourney;
  document.onkeydown=onKeyDownHandler;
  window.onresize=onResizeHandler;
  // the map
  if (isset(document.getElementById(nameMap.id))) { initializeMAP(nameMap);}
  // Premier déclenchement de la fonction dans 200 millisecondes
  setTimeout("mainLoop()",time_mainLopp)
}

// Fonction init pour le formulaire et le bouton submit mais sans la cartte
function initAutoCompleteNoMap(form,submit,lat,lon,villes){
  _documentForm=form;
  _documentForm.autocomplete="off";
  initAutoCompleteVilles(villes);
  latDefault = lat;
  lonDefault = lon;
  affi = document.getElementById("box");
  document.onkeydown=onKeyDownHandler;
  window.onresize=onResizeHandler;
  // Premier déclenchement de la fonction dans 200 millisecondes
  setTimeout("mainLoop()",time_mainLopp)
}


// Fonction init pour les differentes ville
function initAutoCompleteVilles(fields){
  _inputFieldName= fields;
  for (boucle=0; boucle<_inputFieldName.length; boucle++) {
    nameId = _inputFieldName[boucle];
    _inputField = document.getElementById(nameId);
    _inputField.autocomplete="off";
    _currentInputFieldValue[boucle]=_inputField.value[boucle];
    _oldInputFieldValue[boucle]=_currentInputFieldValue[boucle];
    initCacheResults(boucle);
    // _inputField.addEventListener("onkeyup",onKeyUpHandler,false);
    // _inputField.addEventListener("onblur",onBlurHandler,false);
    _inputField.onkeyup=onKeyUpHandler;
    _inputField.onblur=onBlurHandler;
	  _inputField.onfocus=onFocusHandler;
	  _inputField.disabled = false;
    creeAutocompletionDiv(boucle);
  }
  if (document.addEventListener) { /* Mozilla */
    window.addEventListener("onresize",onResizeHandler,false);
  } else { /* IE */
    window.onresize=onResizeHandler;
  }
  // Premier déclenchement de la fonction dans 200 millisecondes
  setTimeout("mainLoop()",time_mainLopp)
}

function offAjaxCityField(CityField) {
  var t = 1;
  _CityField = document.getElementById(CityField); 
	var posCityField = - 1;
  for (ll=0; ll<_inputFieldName.length; ll++) {
    if ( _inputFieldName[ll] == CityField) { posCityField = ll; }
  }
  // _inputFieldName.indexOf(CityField);
  _inputFieldName.splice(posCityField,1);
  _currentInputFieldValue.splice(posCityField,1);
  _oldInputFieldValue.splice(posCityField,1);
  _CityField.onkeyup= '';
  _CityField.onblur='';
	_CityField.onfocus='';
	_CityField.disabled=false;
	var u = 2; 
}

function onAjaxCityField(CityField) { 
    _inputFieldName.push(CityField);
    _inputField = document.getElementById(nameId);
    _inputField.autocomplete="off";
    creeAutocompletionDiv(_inputFieldName.length-1);
    _currentInputFieldValue[_inputFieldName.length]=_inputField.value[_inputFieldName.length];
    _oldInputFieldValue[_inputFieldName.length]=_currentInputFieldValue[_inputFieldName.length];
    initCacheResults(_inputFieldName.length);
    _inputField.onkeyup=onKeyUpHandler;
    _inputField.onblur=onBlurHandler;
	  _inputField.onfocus=onFocusHandler;
	  _inputField.disabled = false;
  if (document.addEventListener) { /* Mozilla */
    window.addEventListener("onresize",onResizeHandler,false);
  } else { /* IE */
    window.onresize=onResizeHandler;
  }
  // Premier déclenchement de la fonction dans 200 millisecondes
  setTimeout("mainLoop()",time_mainLopp)
}


// tourne en permanence pour suggerer suite à un changement du champ texte
function mainLoop(){
  for (jj=0; jj<_inputFieldName.length; jj++) {
    if(_oldInputFieldValue[jj] !=_currentInputFieldValue[jj]){
	  if ( _currentInputFieldValue[jj].length >= 2) {
			nameId = _inputFieldName[jj];
      _inputField = document.getElementById(nameId);
      var valeur=escapeURI(_currentInputFieldValue[jj]);
    	// teste si l internaute souhaite chercher une autre ville
    	// tant que le champ texte debute par le nom complet de la ville
    	// on considere que l internaute ne souhaite pas changer de ville
    	NameOnlyForm = document.getElementById("nameOnly_" + _inputFieldName[jj]).value;
    	NameOnlyForm = escapeURI(NameOnlyForm);
		  lengthNameOnly = NameOnlyForm.length;
    	var changeVille = true; 
		  if (_oldInputFieldValue[jj] == "undefined") { 
			  changeVille=false;
		  } else {
		    if (!(_currentInputFieldValue[jj] == "undefined")) {
					if (valeur.substring(0,lengthNameOnly) == NameOnlyForm &&
				     (_currentInputFieldValue[jj].length <= _oldInputFieldValue[jj].length) ) {
		    	    changeVille = false;   	  
		    	  } 
				  if ( (valeur.substring(0,lengthNameOnly) == NameOnlyForm) &&
				     (_currentInputFieldValue[jj].lastIndexOf(' - ') > 0) ) {
					 changeVille = false;
				  }
		    } else {
		      changeVille = false;
			  }
			}
		  
    	if ( changeVille || NameOnlyForm == '' ) {
    	      // on change de ville
    		  // mettre a zero codeVille, le nom de la ville et le libelle complet avec le pays et le code postal pour la France
            valeurClean = valeur.replace(/%20/g, " ");
	          valeurClean = valeurClean.replace(/%2F/g, '/');
	          // _inputField.value = valeurClean;
		        _inputField.focus();
	  		  storeCodeVille = document.getElementById("codeVille_" + _inputFieldName[jj] );
     	    storeCodeVille.value = '';
    		  storeNameOnly = document.getElementById("nameOnly_" + _inputFieldName[jj]);
    		  storeNameOnly.value = '';
			    storeNomVilleComplet = document.getElementById("nomVilleComplet_" + _inputFieldName[jj]);
    		  storeNomVilleComplet.value = '';
  			  storeCodePays = document.getElementById("code_pays_" + _inputFieldName[jj]);
    		  storeCodePays.value = '';
  			  storeLon = document.getElementById("lon_" + _inputFieldName[jj]);
    	    storeLon.value = '';
		      storeLat = document.getElementById("lat_" + _inputFieldName[jj] );
    	    storeLat.value = '';
          suggestions = false;
				  //if(suggestions){ // la réponse était encore dans le cache
	        //        metsEnPlace(valeur,suggestions,jj)
	        // }else{
				    _completeDiv = document.getElementById("completeDiv_"+jj);
	  				while(_completeDiv.childNodes.length>0) {
	    				_completeDiv.removeChild(_completeDiv.childNodes[0]);
	          }
	     			var nouveauDiv=document.createElement("DIV");
            setStylePourElement(nouveauDiv,"AutoCompleteDiv");
	          var nouveauSpan=document.createElement("SPAN");
	          if (document.getElementById('lang').value == 'FR') {
	            nouveauSpan.innerHTML = "recherche...";
	          } else if (document.getElementById('lang').value == 'FR') {
	            nouveauSpan.innerHTML = "searching...";
	          }
	          nouveauDiv.appendChild(nouveauSpan);
	          _completeDiv.appendChild(nouveauDiv);
	          callSuggestions(valeurClean,jj) // appel distant
	        // }
    	  }
        
				} else {
		      storeCodeVille = document.getElementById("codeVille_" + _inputFieldName[jj]);
       	  storeCodeVille.value = '';
    	    storeNameOnly = document.getElementById("nameOnly_" + _inputFieldName[jj] );
    	    storeNameOnly.value = '';
		      storeNomVilleComplet = document.getElementById("nomVilleComplet_" + _inputFieldName[jj] );
    	    storeNomVilleComplet.value = '';
		      storeLon = document.getElementById("lon_" + _inputFieldName[jj]);
    	    storeLon.value = '';
		      storeLat = document.getElementById("lat_" + _inputFieldName[jj] );
  	      storeLat.value = '';
		      _completeDiv = document.getElementById("completeDiv_"+jj);
		      // on efface la completion
		      while(_completeDiv.childNodes.length>0) {
    		    _completeDiv.removeChild(_completeDiv.childNodes[0]);
          }
		      hideCompleteDiv(_completeDiv,jj);
		  // on positionne la carte sur la ville par defaut
          // positionnement de la carte Google
	      // var map = new GMap2(document.getElementById("map"));
 	       if (isset(map)) {map.setCenter(new GLatLng(latDefault, lonDefault), 10)};
	     }
	  }
    _oldInputFieldValue[jj]=_currentInputFieldValue[jj];
  }  
  setTimeout("mainLoop()",time_mainLopp); // la fonction se redéclenchera dans 200 ms
  return true
}

// echappe les caractère spéciaux
function escapeURI(La){
  if(encodeURIComponent) {
    return encodeURIComponent(La);
  }
  if(escape) {
    return escape(La)
  }
}

function callSuggestions(valeur,index){
  if(_xmlHttp&&_xmlHttp.readyState!=0){
    _xmlHttp.abort()
  }
  _xmlHttp=getXMLHTTP();
  if(_xmlHttp){
    //appel à l'url distante
    language = document.getElementById('lang').value;
    radio = document.getElementById("typeResearch_" + _inputFieldName[index]);
    // par defaut on recherche les villes commencant par
    methode = 1;
    if (!(radio ==  null)) {
    for (var i=0; i<radio.length;i++) {
           if (radio[i].checked) {
              methode = radio[i].value;
           }
    }
    } 
	adresseAppel = _adresseRecherche+"?debut="+valeur+"&methode="+methode+"&language="+language;
    _xmlHttp.open("GET",adresseAppel,true);
    _xmlHttp.onreadystatechange=function() {
      if(_xmlHttp.readyState==4&&_xmlHttp.responseXML) {
        var liste = traiteXmlSuggestions(_xmlHttp.responseXML)
        // cacheResults(valeur,liste,index)
        metsEnPlace(valeur,liste,index)
      }
    };
    // envoi de la requete
    _xmlHttp.send(null)
  }
}

// Initialisation du caching des réponses
function initCacheResults(index){
  _resultCache[index] = new Array();
}

// Mecanisme de caching des réponses
function cacheResults(debut,suggestions,index){
  _resultCache[index][debut]=suggestions
}

// Transformation XML en tableau
function traiteXmlSuggestions(xmlDoc) {
  var options = xmlDoc.getElementsByTagName('option');
  var optionsListe = new Array();
  for (var boucle=0; boucle < options.length; ++boucle) {
    // optionsListe.push(options[boucle].firstChild.data);
    if (document.addEventListener) { /* Mozilla */
	// alert(options[boucle].textContent);
      optionsListe.push(options[boucle].textContent); 
    } else { /* IE */
      optionsListe.push(options[boucle].text);
    }
  }
  return optionsListe;
}

// Transformation text en tableau
function traiteTextSuggestions(textDoc) {
  var optionsListe = new Array();
  optionsListe = textDoc.split('<br>');
  return optionsListe;
}

//insère une règle avec son nom
function insereCSS(nom,regle){
  // if (!(document.getElementById('sitepartenaire') == null) || (!(document.getElementById('sitepartenaire').value == 'adia'))) {
	if ((document.getElementById('sitepartenaire').value == 'adia')|| (document.getElementById('sitepartenaire').value == 'sitesblanc')) {
	if (document.styleSheets) {
	  var gg = 0;
		while ((gg < document.styleSheets.length) && (document.styleSheets[gg].href != "http://www.covoiturage.com/elt/style_adia.css")) {
			gg++;
    }
    I = document.styleSheets[gg];
    if(I.addRule){ // méthode IE
      I.addRule(nom,regle)
    } else if(I.insertRule) { // méthode DOM
			    I.insertRule(nom+" { "+regle+" }",I.cssRules.length)      
    } else {
        I.insertRule(nom+" { "+regle+" }",I.cssRules.length)
    }
  }
  } else {
  if (document.styleSheets) {
	  var gg = 0;
		while ( (gg < document.styleSheets.length) && (document.styleSheets[gg].href != "http://www.covoiturage.com/elt/stylesnc.css" ) ) {
			gg++;
    }
    var I = document.styleSheets[gg];
    if(I.addRule){ // méthode IE
      I.addRule(nom,regle)
    } else if(I.insertRule) { // méthode DOM
			    I.insertRule(nom+" { "+regle+" }",I.cssRules.length)      
    } else {
        I.insertRule(nom+" { "+regle+" }",I.cssRules.length)
    }
  }
	}
  //}
}

function insereCSSOld(nom,regle){
  if (!(document.getElementById('sitepartenaire') == null) || (!(document.getElementById('sitepartenaire').value == 'adia'))|| (!(document.getElementById('sitepartenaire').value == 'sitesblanc')) ) {
	if (document.styleSheets) {
	  var gg = 0;
		while ( (gg < document.styleSheets.length) && (document.styleSheets[gg].href != "http://www.covoiturage.com/elt/stylesnc.css" ) ) {
			gg++;
    }
    var I = document.styleSheets[gg];
    if(I.addRule){ // méthode IE
      I.addRule(nom,regle)
    } else if(I.insertRule) { // méthode DOM
			    I.insertRule(nom+" { "+regle+" }",I.cssRules.length)      
    } else {
        I.insertRule(nom+" { "+regle+" }",I.cssRules.length)
    }
  }
  }
}


function initStyle(){
  var AutoCompleteDivListeStyle="font-size: 13px; font-family: arial,sans-serif; word-wrap:break-word; ";
  var AutoCompleteDivStyle="display: block; padding-left: 3; padding-right: 3; height: 16px; overflow: hidden; background-color: white;";
  var AutoCompleteDivActStyle="background-color: #3366cc; color: white ! important; ";
  insereCSS(".AutoCompleteDivListeStyle",AutoCompleteDivListeStyle);
  insereCSS(".AutoCompleteDiv",AutoCompleteDivStyle);
  insereCSS(".AutoCompleteDivAct",AutoCompleteDivActStyle);
}

function setStylePourElement(c,name){
  c.className=name;
}

// calcule le décalage à gauche
function calculateOffsetLeft(r){
  return calculateOffset(r,"offsetLeft")
}

// 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
}

// calcule la largeur du champ
function calculateWidth(_inputField){
  if (_inputField.offsetWidth != 0) {
    return _inputField.offsetWidth-2*1;
  } else {
    return 10;
	}
}

function setCompleteDivSize(_completeDiv,index){
  _inputField = document.getElementById(_inputFieldName[index]);
  if(_completeDiv){
    _completeDiv.style.left=calculateOffsetLeft(_inputField)+"px";
    posTopStyle =calculateOffsetTop(_inputField) + _inputField.offsetHeight -1 + "px" ;
    // _completeDiv.style.top= _completeDiv.style.top + _inputField.offsetHeight -1 + "px";
    _completeDiv.style.top= posTopStyle;
    _completeDiv.style.width=calculateWidth(_inputField)+"px"
  }
}

function creeAutocompletionDiv(cursor) {
  initStyle();
  _completeDiv=document.createElement("DIV");
  _completeDiv.id="completeDiv_"+cursor;
  var borderLeftRight=1;
  var borderTopBottom=1;
  _completeDiv.style.borderRight="black "+borderLeftRight+"px solid";
  _completeDiv.style.borderLeft="black "+borderLeftRight+"px solid";
  _completeDiv.style.borderTop="black "+borderTopBottom+"px solid";
  _completeDiv.style.borderBottom="black "+borderTopBottom+"px solid";
  _completeDiv.style.zIndex="1";
  _completeDiv.style.paddingRight="0";
  _completeDiv.style.paddingLeft="0";
  _completeDiv.style.paddingTop="0";
  _completeDiv.style.paddingBottom="0";
  setCompleteDivSize(_completeDiv, cursor);
  _completeDiv.style.visibility="hidden";
  _completeDiv.style.position="absolute";
  _completeDiv.style.backgroundColor="white";
  document.body.appendChild(_completeDiv);
  setStylePourElement(_completeDiv,"AutoCompleteDivListeStyle");
}

function getInitCountry(nameC) {
  var tabNameCountry = new Array();
  var codeFR = null;
  var codeDE = null;
  var codeGB = null;
  var codeIT = null;
  var codeES = null;
  var codePT = null;
  var codeBE = null;
  var codeNL = null;
  var codeCH = null;
  var codeAT = null;
  var codeLU = null;
  var codeCA = null;
  var codeUS = null;
  var codeIN = null;
  var codeSK = null;
  var codePL = null;
  var codeGR = null;
  var codeHR = null;
  var codeCZ = null;
  var codeIE = null;
  var codeRO = null;
  var codeSI = null;
  var codeTN = null;
  var codeDZ = null;
  var codeMA = null;
  var codeHU = null;
  var codeAL = null;
  var codeME = null;
  var codeRS = null;
  var codeAD = null;
  var codeBA = null;
  var codeMC = null;
  var codeMQ = null;
  var codeGP = null;
  
  if (document.getElementById('lang').value == 'FR') {
    nameFR = 'France';
    nameDE = 'Allemagne';
    nameGB = 'Grande-Bret';
    nameIT = 'Italie';
    nameES = 'Espagne';
    namePT = 'Portugal';
    nameBE = 'Belgique';
    nameNL = 'Pays-Bas';
    nameCH = 'Suisse';
    nameAT = 'Autriche';
    nameLU = 'Luxembourg';
	nameCA = 'Canada';
	nameUS = 'Etats-Unis';
	nameIN = 'Inde';
	nameSK = 'Slovaquie';
	namePL = 'Pologne';
	nameGR = 'Grece';
	nameHR = 'Croatie';
	nameCZ = 'Replublie Tcheque';
	nameIE = 'Irelande';
	nameRO = 'Roumanie';
	nameSI = 'Slovenie';
	nameTN = 'Tunisie';
	nameDZ = 'Algerie';
	nameMA = 'Maroc';
	nameHU = 'Hongrie';
	nameAL = 'Albanie';
	nameME = 'Mont&eacute;negro';
	nameRS = 'Serbie';
	nameAD = 'Andorre';
	nameBA = 'Bosnie et Herz&eacute;govine';
	nameMC = 'Monaco';
	nameMQ = 'Martinique';
	nameGP = 'Guadeloupe';
	
  }
  if (document.getElementById('lang').value == 'UK') {
    nameFR = 'France';
    nameDE = 'Germany';
    nameGB = 'UK';
    nameIT = 'Italy';
    nameES = 'Spain';
    namePT = 'Portugal';
    nameBE = 'Belgium';
    nameNL = 'Netherlands';
    nameCH = 'Switzerland';
    nameAT = 'Austria';
    nameLU = 'Luxembourg';
	nameCA = 'Canada';
	nameUS = 'USA';
	nameIN = 'India';
	nameSK = 'Slovakia';
	namePL = 'Poland';
	nameGR = 'Greece';
	nameHR = 'Croatia';
	nameCZ = 'Czech Republic';
	nameIE = 'Ireland';
	nameRO = 'Romania';
	nameSI = 'Slovenia';
	nameTN = 'Tunisia';
	nameDZ = 'Algeria';
	nameMA = 'Maroco';
	nameHU = 'Hungary';
	nameAL = 'Albany';
	nameME = 'Montenegro';
	nameRS = 'Serbia';
	nameAD = 'Andorra';
	nameBA = 'Bosnia and Herzegovina';
	nameMC = 'Monaco';
	nameMQ = 'Martinique';
	nameGP = 'Guadeloupe';
  }
  tabNameCountry[nameFR] = 'FR';
  tabNameCountry[nameDE] = 'DE';
  tabNameCountry[nameGB] = 'GB';
  tabNameCountry[nameIT] = 'IT';
  tabNameCountry[nameES] = 'ES';
  tabNameCountry[namePT] = 'PT';
  tabNameCountry[nameBE] = 'BE';
  tabNameCountry[nameNL] = 'NL';
  tabNameCountry[nameCH] = 'CH';
  tabNameCountry[nameAT] = 'AT';
  tabNameCountry[nameLU] = 'LU';
  tabNameCountry[nameCA] = 'CA';
  tabNameCountry[nameUS] = 'US';
  tabNameCountry[nameIN] = 'IN';
  tabNameCountry[nameSK] = 'SK';
  tabNameCountry[namePL] = 'PL';
  tabNameCountry[nameGR] = 'GR';
  tabNameCountry[nameHR] = 'HR';
  tabNameCountry[nameCZ] = 'CZ';
  tabNameCountry[nameIE] = 'IE';
  tabNameCountry[nameRO] = 'RO';
  tabNameCountry[nameSI] = 'SI';
  tabNameCountry[nameTN] = 'TN';
  tabNameCountry[nameDZ] = 'DZ';
  tabNameCountry[nameMA] = 'MA';
  tabNameCountry[nameHU] = 'HU';
  tabNameCountry[nameAL] = 'AL';
  tabNameCountry[nameME] = 'ME';
  tabNameCountry[nameRS] = 'RS';
  tabNameCountry[nameAD] = 'AD';
  tabNameCountry[nameBA] = 'BA';
  tabNameCountry[nameMC] = 'MC';
  tabNameCountry[nameMQ] = 'MQ';
  tabNameCountry[nameGP] = 'GP';
  return tabNameCountry[nameC];
}

function getNameCountry(cCode) {
  var tabCodeCountry = new Array();
  var codeFR = null;
  var codeDE = null;
  var codeGB = null;
  var codeIT = null;
  var codeES = null;
  var codePT = null;
  var codeBE = null;
  var codeNL = null;
  var codeCH = null;
  var codeAT = null;
  var codeLU = null;
  var codeCH = null;
  var codeCA = null;
  var codeUS = null;
  var codeIN = null;
  var codeSK = null;
  var codePL = null;
  var codeGR = null;
  var codeHR = null;
  var codeCZ = null;
  var codeIE = null;
  var codeRO = null;
  var codeSI = null;
  var codeTN = null;
  var codeDZ = null;
  var codeMA = null;
  var codeHU = null;
  var codeAL = null;
  var codeME = null;
  var codeRS = null;
  var codeAD = null;
  var codeBA = null;
  var codeMC = null;
  var codeMQ = null;
  var codeGP = null;
  
  codeFR = 'FR';
  codeDE = 'DE';
  codeGB = 'GB';
  codeIT = 'IT';
  codeES = 'ES';
  codePT = 'PT';
  codeBE = 'BE';
  codeNL = 'NL';
  codeCH = 'CH';
  codeAT = 'AT';
  codeLU = 'LU';
  codeCA = 'CA';
  codeUS = 'US';
  codeIN = 'IN';
  codeSK = 'SK';
  codePL = 'PL';
  codeGR = 'GR';
  codeHR = 'HR';
  codeCZ = 'CZ';
  codeIE = 'IE';
  codeRO = 'RO';
  codeSI = 'SI';
  codeTN = 'TN';
  codeDZ = 'DZ';
  codeMA = 'MA';
  codeHU = 'HU';
  codeAL = 'AL';
  codeME = 'ME';
  codeRS = 'RS';
  codeAD = 'AD';
  codeBA = 'BA';
  codeMC = 'MC';
  codeMQ = 'MQ';
  codeGP = 'GP';
  
  if (document.getElementById('lang').value == 'FR') {
    tabCodeCountry[codeFR] = 'France';
    tabCodeCountry[codeDE] = 'Allemagne';
    tabCodeCountry[codeGB] = 'Grande-Bret';
    tabCodeCountry[codeIT] = 'Italie';
    tabCodeCountry[codeES] = 'Espagne';
    tabCodeCountry[codePT] = 'Portugal';
    tabCodeCountry[codeBE] = 'Belgique';
    tabCodeCountry[codeNL] = 'Pays-Bas';
    tabCodeCountry[codeCH] = 'Suisse';
    tabCodeCountry[codeAT] = 'Autriche';  
    tabCodeCountry[codeLU] = 'Luxembourg';
    tabCodeCountry[codeCA] = 'Canada';
    tabCodeCountry[codeUS] = 'Etats-Unis';
    tabCodeCountry[codeIN] = 'Inde';
    tabCodeCountry[codeSK] = 'Slovaquie';
    tabCodeCountry[codePL] = 'Pologne';
    tabCodeCountry[codeGR] = 'Grece';
    tabCodeCountry[codeHR] = 'Croatie';
    tabCodeCountry[codeCZ] = 'Replublique Tcheque';
    tabCodeCountry[codeIE] = 'Irelande';
    tabCodeCountry[codeRO] = 'Roumanie';
    tabCodeCountry[codeSI] = 'Slovenie';
	tabCodeCountry[codeTN] = 'Tunisie';
	tabCodeCountry[codeDZ] = 'Algerie';
	tabCodeCountry[codeMA] = 'Maroc';
	tabCodeCountry[codeHU] = 'Hongrie';
    tabCodeCountry[codeAL] = 'Albanie';
	tabCodeCountry[codeME] = 'Mont&eacute;negro';
 	tabCodeCountry[codeRS] = 'Serbie';
	tabCodeCountry[codeAD] = 'Andorre';
	tabCodeCountry[codeBA] = 'Bosnie et Herz&eacute;govine';
	tabCodeCountry[codeMC] = 'Monaco';
	tabCodeCountry[codeMQ] = 'Martinique';
	tabCodeCountry[codeGP] = 'Guadeloupe';
	
  }
  if (document.getElementById('lang').value == 'UK') {
    tabCodeCountry[codeFR] = 'France';
    tabCodeCountry[codeDE] = 'Germany';
    tabCodeCountry[codeGB] = 'UK';
    tabCodeCountry[codeIT] = 'Italy';
    tabCodeCountry[codeES] = 'Spain';
    tabCodeCountry[codePT] = 'Portugal';
    tabCodeCountry[codeBE] = 'Belgium';
    tabCodeCountry[codeNL] = 'Netherlands';
    tabCodeCountry[codeCH] = 'Switzerland';
    tabCodeCountry[codeAT] = 'Austria';  
    tabCodeCountry[codeLU] = 'Luxembourg';
	tabCodeCountry[codeCA] = 'Canada';
    tabCodeCountry[codeUS] = 'USA';
    tabCodeCountry[codeIN] = 'India';
    tabCodeCountry[codeSK] = 'Slovakia';
    tabCodeCountry[codePL] = 'Poland';
    tabCodeCountry[codeGR] = 'Greece';
    tabCodeCountry[codeHR] = 'Croatia';
    tabCodeCountry[codeCZ] = 'Czech Republic';
    tabCodeCountry[codeIE] = 'Ireland';
    tabCodeCountry[codeRO] = 'Romania';
    tabCodeCountry[codeSI] = 'Slovenia';
	tabCodeCountry[codeTN] = 'Tunisia';
	tabCodeCountry[codeDZ] = 'Algeria';
	tabCodeCountry[codeMA] = 'Maroco';
	tabCodeCountry[codeHU] = 'Hungary';
	tabCodeCountry[codeAL] = 'Albany';
	tabCodeCountry[codeME] = 'Montenegro';
    tabCodeCountry[codeRS] = 'Serbia';
    tabCodeCountry[codeAD] = 'Andorra';
    tabCodeCountry[codeBA] = 'Bosnia and Herzegovina';
	tabCodeCountry[codeMC] = 'Monaco';
	tabCodeCountry[codeMQ] = 'Martinique';
	tabCodeCountry[codeGP] = 'Guadeloupe';

  }
return tabCodeCountry[cCode];
}

function metsEnPlace(valeur, liste, index){
  _completeDiv = document.getElementById("completeDiv_"+index);
  while(_completeDiv.childNodes.length>0) {
    _completeDiv.removeChild(_completeDiv.childNodes[0]);
  }
  // mise en place des suggestions
  // on renseigne les champs codeGeo et nameOnly
  var ancienTexteVille = '';
  var ancienCodePostal = '';
  var first = 0;
  for(var f=0; f<liste.length; ++f){
    var nouveauDiv=document.createElement("DIV");
    nouveauDiv.onmousedown=divOnMouseDown;
	  // nouveauDiv.onmouseover=divOnMouseOver;
    nouveauDiv.onmouseout=divOnMouseOut;
    setStylePourElement(nouveauDiv,"AutoCompleteDiv");
    var nouveauSpan=document.createElement("SPAN");
    // on extrait le code postal
	  allDetails = liste[f].split('/SEPA/');
	  iconSpe = allDetails[6];
	  codePostal = allDetails[5];
	  // on extrait la latitude et longitude
	  longitude = allDetails[4];
	  latitude = allDetails[3];
    countryCode = allDetails[2];
    codeGeoId = allDetails[1];
	  texteVille = allDetails[0];
	
		// mise a jour du champ text du div avec la reference au pays
		// le texte de la suggestion
		// VERSION : 15 DECEMBRE le champ code postal est toujours affiche
		champCP = '';
		
		if (codePostal != '') {
		  champCP = ' (' + codePostal + ')';
		}
	
	  texteSugg = texteVille + champCP + " - " + getNameCountry(countryCode);
    nouveauSpan.innerHTML = texteSugg;
	  ancienTexteVille = texteVille;
	
	  idDiv = texteVille + "/SEPA/" + codeGeoId + "/SEPA/" + latitude + "/SEPA/" + longitude + "/SEPA/" + countryCode + "/SEPA/" + iconSpe;
    nouveauDiv.id = idDiv;
    nouveauDiv.appendChild(nouveauSpan);
    _completeDiv.appendChild(nouveauDiv)
	  ancienCodePostal = codePostal;
  }
  PressAction(index);
  if(_completeDivRows[index]>0) {
    _completeDiv.height=16*_completeDivRows[index]+4;
  } else {
    hideCompleteDiv(_completeDiv, index);
  }

}

var _lastKeyCode=null;

// Handler pour le keydown du document
var onKeyDownHandler=function(event){
  // accès evenement compatible IE
  if(!event&&window.event) {
    event=window.event;
    // on enregistre la touche ayant déclenché l'evenement
    if(event) {
      _lastKeyCode=event.keyCode;
    }
  } else if (!event&&event.which) { /* Compatibilite Firefox */
    // on enregistre la touche ayant déclenché l'evenement
    _lastKeyCode=event.which;
  }
}

// Handler pour le keyup de lu champ texte
var onKeyUpHandler=function(event){ 
  _inputField = document.getElementById(this.name);
  var index = - 1;
  for (ll=0; ll<_inputFieldName.length; ll++) {
    if ( _inputFieldName[ll] == this.name) { index = ll; }
  }
  // accès evenement compatible IE
  // _eventKeycode=event.keyCode;
  if(!event&&window.event) {
    event=window.event;
    _eventKeycode=event.keyCode;
  } else if (event.which) { /* Compatibilite Firefox */
    // on enregistre la touche ayant déclenché l'evenement
    _eventKeycode=event.which;
  }
  // Dans les cas touches touche haute(38) ou touche basse (40)
  if(_eventKeycode==40||_eventKeycode==38||_eventKeycode==9) {
    // on autorise le blur du champ (traitement dans onblur)
    blurThenGetFocus(_inputField, index);
  }
  // taille de la selection
  var N=rangeSize(_inputField);
  // taille du texte avant la selection (selection = suggestion d'autocomplétion)
  var v=beforeRangeSize(_inputField);
  // contenu du champ texte
  var V=_inputField.value;
  if(_eventKeycode!=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==13||_eventKeycode==3){
	  var index = - 1;
      for (ll=0; ll<_inputFieldName.length; ll++) {
       if ( _inputFieldName[ll] == _inputField.name) { index = ll; }
      }
      _completeDiv = document.getElementById("completeDiv_" + index);
      // recherche la position dans la liste deroulante de 
      // la ville selectionnee
      rechercheVille = this.id;
		  // enleve le pays
		  rechercheVille = rechercheVille.substring(0,rechercheVille.lastIndexOf(" - "));
		  goOn = true;
		  nn = 0;
	    while( (nn<_completeDiv.childNodes.length && goOn)) {
		    infoVilleId =  _completeDiv.childNodes[nn].id
	        // infoVille = infoVille.substring(0,infoVille.lastIndexOf(" - "));
	        // infoVille = infoVille.substring(0,infoVille.lastIndexOf(" - "));
			// keyVille = infoVille.substring(infoVille.lastIndexOf(" - ")+3,infoVille.length);
			// texteVille = infoVille.substring(0,infoVille.lastIndexOf(" - "));
	      if ( rechercheVille == infoVilleId) { 
		        _highlightedSuggestionIndex[index] = nn;
			      goOn = false;
		    } else {
			     nn++;
			  }  
	    } 
	    highlightNewValue(_highlightedSuggestionIndex[index], index);
		  hideCompleteDiv(_completeDiv, index);
	    var d=_inputField;
	    // on mets en place l'ensemble du champ texte en repoussant la selection
	    if(_inputField.createTextRange){
	      var t=_inputField.createTextRange();
	      t.moveStart("character",_inputField.value.length);
	      _inputField.select()
      } else if (d.setSelectionRange){
			  _inputField.setSelectionRange(_inputField.value.length,_inputField.value.length)
      }
      showJourney();
    } else {
      // si on a pas pu agrandir le champ non selectionné, on le met en place violemment.
      if(_inputField.value!=V) {
        _inputField.value=V
      }
    }
  }
  // si la touche n'est ni haut, ni bas, on stocke la valeur utilisateur du champ
  if(_eventKeycode!=40&&_eventKeycode!=38) {
    // le champ courant n est pas change si key Up ou key Down
  	_currentInputFieldValue[index]=V;
  }
  if(handleCursorUpDownEnterRight(_eventKeycode,index)&&_eventKeycode!=0) {
    // si on a préssé une touche autre que haut bas enter right
    PressAction(index);
  }
}

// Change la suggestion selectionné.
// cette méthode traite les touches haut, bas et enter
function handleCursorUpDownEnterRight(eventCode,index){
  if (eventCode==8) {
    return false;
  }else if(eventCode==40){
    highlightNewValue(_highlightedSuggestionIndex[index]+1,index);
    return false
  }else if(eventCode==38){
    highlightNewValue(_highlightedSuggestionIndex[index]-1,index);
    return false
  } else if(eventCode==13||eventCode==3){
    highlightNewValue(_highlightedSuggestionIndex[index], index);
	hideCompleteDiv(_completeDiv, index);
    _oldInputFieldValue[index]=_currentInputFieldValue[index];
    
	return false
  } else if(eventCode==39) {
    // cursor right
	// on efface la selection
	// on s assure que les champs geonameid, codepays et nameOnly sont bien mis
	// a jour
	highlightNewValue(_highlightedSuggestionIndex[index], index);
	hideCompleteDiv(_completeDiv, index);
    _oldInputFieldValue[index]=_currentInputFieldValue[index];
    return false
  }
  return true
}

function handleCursorEnterRightNoAction(eventCode,index){
  if (eventCode==39 || eventCode==13 || eventCode==3) {
    return false;
  }
  return true
}

// gère une touche pressée autre que haut/bas/enter
function PressAction(cursor){

  var _inputField = document.getElementById(_inputFieldName[cursor]);
  var _completeDiv = document.getElementById("completeDiv_" + cursor);
  _highlightedSuggestionIndex[cursor]=-1;
  var suggestionList=_completeDiv.getElementsByTagName("div");
  var suggestionLongueur=suggestionList.length;
  // on stocke les valeurs précédentes
  // nombre de possibilités de complétion
  _completeDivRows[cursor]=suggestionLongueur;
  // possiblités de complétion
  _completeDivDivList[cursor]=suggestionList;
  // si le champ est vide, on cache les propositions de complétion
  if(_currentInputFieldValue[cursor].length<2||suggestionLongueur==0){
    hideCompleteDiv(_completeDiv, cursor)
  }else{
    showCompleteDiv(_completeDiv, cursor)
  }
  var trouve=false;
  // si on a du texte sur lequel travailler
  if(_currentInputFieldValue[cursor].length>=2){
    var indice;
    // Trouver 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(suggestionList.item(indice)).toUpperCase().indexOf(_currentInputFieldValue[cursor].toUpperCase())==0) {
        trouve=true;
        break;
      }
    }
  }
  // on désélectionne toutes les suggestions
  for(var i=0; i<suggestionLongueur; i++) {
    setStylePourElement(suggestionList.item(i),"AutoCompleteDiv");
  }
  // 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[cursor]=indice;
    _highlightedSuggestionDiv[cursor]=suggestionList.item(_highlightedSuggestionIndex[cursor]);
    // highlightNewValue(_highlightedSuggestionIndex[cursor], cursor);
  }else{
    _highlightedSuggestionIndex[cursor]=-1;
    _highlightedSuggestionDiv[cursor]=null
  }
  var supprSelection=false;
  switch(_eventKeycode){
    // cursor left, page up, page down, others??
	case 9:
	  // tab
    //  alert(cursor);
			forceInputField = document.getElementById("nomVilleComplet_"+_inputFieldName[cursor]);
	    _inputField.value = forceInputField.value;
	    cursorAfterValue(_inputField);
	    _currentInputFieldValue[cursor] = _inputField.value.lenght;
	    _oldInputFieldValue[cursor] = _currentInputFieldValue[cursor];
	  break;  
	case 33:
    case 34:
    case 35:
    case 35:
    case 36:
    case 37:
    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[cursor]){
	setStylePourElement(_highlightedSuggestionDiv[cursor],"AutoCompleteDivAct");
    var z;
    if(trouve) {
      z=getSuggestion(_highlightedSuggestionDiv[cursor]).substr(0);
    } else {
      z=_currentInputFieldValue[cursor];
    }
    if(z!=_inputField.value){
      if(_inputField.value!=_currentInputFieldValue[cursor]) {
        return;
      }
      // si on peut créer des range dans le document
      if(_inputField.createTextRange||_inputField.setSelectionRange) {
        // _inputField.value=z;
        posSelectionDiv = 0;
        highlightNewValue(posSelectionDiv,cursor);
      }
	  // on sélectionne la fin de la suggestion
      if(_inputField.createTextRange){
	    // Internet Explorer
        var t=_inputField.createTextRange();
        t.moveStart("character",_currentInputFieldValue[cursor].length);
        t.select()
      }else if(_inputField.setSelectionRange){
	    // Firefox
        _inputField.setSelectionRange(_currentInputFieldValue[cursor].length,_inputField.value.length)
      }
    }
  }else{
    // sinon, plus aucune suggestion de sélectionnée
    _highlightedSuggestionIndex[cursor]=-1;
  }
}

// permet le blur du champ texte après que la touche haut/bas ait été pressée.
// le focus est récupéré après traitement (via le timeout).
function blurThenGetFocus(){
  _cursorUpDownPressed=true;
  _inputField.blur();
  setTimeout("_inputField.focus();",10);
  return
}

// taille de la selection dans le champ input
function rangeSize(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(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+1
  }else{
    v=-1
  }
  return v
}

// Place le curseur à la fin du champ
function cursorAfterValue(n){
  if(n.createTextRange){
    var t=n.createTextRange();
    t.moveStart("character",n.value.length+1);
    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(uneDiv){
  if(!uneDiv) {
    return null;
  }
  return trimCR(uneDiv.getElementsByTagName('span')[0].firstChild.data)
}

// supprime les caractères retour chariot et line feed d'une chaine de caractères
function trimCR(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(_completeDiv, pos){
  _completeDiv.style.visibility="hidden"
  // showJourney();
}

// Rends les choix de completion visibles
function showCompleteDiv(_completeDiv, pos){
  _completeDiv.style.visibility="visible";
  setCompleteDivSize(_completeDiv, pos)
}

// Change la suggestion en surbrillance
function highlightNewValue(C, pos){
  _inputField = document.getElementById(_inputFieldName[pos]);
  _completeDiv = document.getElementById("completeDiv_" + pos);
  if(!_completeDivDivList[pos]||_completeDivRows[pos]<=0) {
    return;
  }
  showCompleteDiv(_completeDiv, pos);
  if(C>=_completeDivRows[pos]){
    C=_completeDivRows[pos]-1
  }
  if(_highlightedSuggestionIndex[pos]!=-1&&C!=_highlightedSuggestionIndex[pos]){
    setStylePourElement(_highlightedSuggestionDiv[pos],"AutoCompleteDiv");
    _highlightedSuggestionIndex[pos]=-1
  }
  if(C<0){
    _highlightedSuggestionIndex[pos]=-1;
    _inputField.focus();
    return;
  }
  // document.getElementById(''posCur.value = infoVille;
  _highlightedSuggestionIndex[pos]=C;
  _highlightedSuggestionDiv[pos]=_completeDivDivList[pos].item(C);
 
  infoVille = _completeDivDivList[pos].item(C).id;
   
  // on extrait la latitude et la longitude
  allDetails = infoVille.split('/SEPA/');
  
  iconToShow = allDetails[5]; 
  countryCode = allDetails[4];
  longitude = allDetails[3];  
  latitude = allDetails[2];
  keyVille = allDetails[1];
  texteVille = allDetails[0];
  
  // mise a jour du champ d entree
  if(!(handleCursorEnterRightNoAction(_eventKeycode,pos)&&_eventKeycode!=0)) {
    _inputField.value=getSuggestion(_highlightedSuggestionDiv[pos]);
  }
	// mise a jour du code geonameid
	storeCodeVille = document.getElementById("codeVille_"+_inputFieldName[pos]);
  storeCodeVille.value = keyVille;
  
  // mise a jour du champ nameOnly sans la reference au pays
  var nameVille = document.getElementById("nameOnly_" + _inputFieldName[pos]);
  nameVille.value = texteVille;
  setStylePourElement(_highlightedSuggestionDiv[pos],"AutoCompleteDivAct");
    
	// mise a jour du champ nom de ville complet
  var nameVilleComplet = document.getElementById("nomVilleComplet_" + _inputFieldName[pos]);
  nameVilleComplet.value = getSuggestion(_highlightedSuggestionDiv[pos]);  
  
	// mise a jour du champ pays
  country = getSuggestion(_highlightedSuggestionDiv[pos]);
  country = country.substring(country.lastIndexOf(" - ")+3,country.length);
  storeCountryCode = document.getElementById("code_pays_"+_inputFieldName[pos]);
  storeCountryCode.value = countryCode;
  
  // mise a jour des champs lat et lon
  storeLat = document.getElementById("lat_"+_inputFieldName[pos]);
  storeLat.value = latitude;
  storeLon = document.getElementById("lon_"+_inputFieldName[pos]);
  storeLon.value = longitude;
  storeIcon = document.getElementById("imageIcon_"+_inputFieldName[pos]);
  storeIcon.value = iconToShow;
  // positionnement de la carte Google
  // var map = new GMap2(document.getElementById("map"));
  if (isset(map)) {
	map.setCenter(new GLatLng(latitude, longitude), 10);
  showJourney();
  }
  // position = map.fromLatLngToDivPixel(new GLatLng(latitude, longitude))
}

function refreshCalculette() {
  if (document.getElementById('liveCalculette').value == 'y') {
    if (document.getElementById('lang').value == 'FR') {
	  var devise = "&euro;";
	} else {
	  if ( document.getElementById('lang').value == 'UK') {
	    var devise = "£";
	  }
	}
	nbPass = document.getElementById('nbr_place_libre').value;
    d = document.getElementById('distance');
    if (d.value == '') {
      d.value = 0;
    }
    document.getElementById('ct_total').value = Math.round(eval(1*document.getElementById('al_couts').value) + eval(d.value) * document.getElementById('conso_km').value * document.getElementById('px_essence').value/100);
    document.getElementById('px_sugg').value = Math.round(document.getElementById('ct_total').value * document.getElementById('tx_couverture').value / 100);
    document.getElementById('px_personne_sugg').innerHTML = Math.round(document.getElementById('px_sugg').value/nbPass) + " " + devise;
    if (eval(d.value) != 0) {
      document.getElementById('px_km').innerHTML = Math.round(100*document.getElementById('px_sugg').value/nbPass/eval(d.value))/100 + " " + devise;
    } else {
      document.getElementById('px_km').innerHTML = '0.10 ' + devise;
    }
    ecoCO2 = document.getElementById('rateCo2_km').value;
    document.getElementById('totalEcoCo2').innerHTML = Math.round(( ecoCO2 * eval(d.value) / nbPass) / 1000) + " kg";
  }
}

function onGDirectionsLoad() {
  distance = _journey.getDistance();
  if (document.getElementById('liveCalculette').value == 'y') {
    document.getElementById('distance').value = Math.round(eval(distance.meters)/1000);
  }
  refreshCalculette();
  var time = _journey.getDuration();
  // divInfoJourney.innerHTML = "<div align=center>Info Journey</div><br>Distance: " + distance.html + "<br>Duration: "+time.html;
  if ( document.getElementById('lang').value == 'UK') {
    divInfoJourney.innerHTML = "<div align=center>Detailed road map</div><br>Distance: " + distance.html + "<br>Time: "+time.html;
	} else if ( document.getElementById('lang').value == 'FR') {
		divInfoJourney.innerHTML = "<div align=center>Itin&eacute;raire d&eacute;taill&eacute;</div><br>Distance : " + distance.html + "<br>Dur&eacute;e : "+time.html;
	}

}

function onGDirectionsAddOverlay(){ 
  // Remove the selection Marker
  if (!(marker==undefined)) {
    map.removeOverlay(marker);
  }
  
  // We zoom out to make sure the journey is correctly displayed and that
  // the destinations are not located in the corners
  map.zoomOut();
  
  // display at the center of the map the marker to select a new city
  // newCenter = map.getCenter();
  // createSelectionMarker(newCenter);
  // map.addOverlay(marker);
  // infoWindow();
  // Add the possibility to click again on the map to have a new selection marker appearing
  // _ClickEventListener = GEvent.addListener(map, "click", getAddress);
 
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }
  
  for (var i=0; i<=_journey.getNumRoutes(); i++){
    icon_spe = document.getElementById('imageIcon_'+_inputFieldName[i]);
	if ( icon_spe.value != 'NOLOGO') {
	  var originalMarker = _journey.getMarker(i);
      latLngs[i] = originalMarker.getLatLng();
      // newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:false, title:''});
      // map.addOverlay(newMarkers[i]);
	  // Bind 'click' event to original markers 'click' event
	  newMarkers[i] = addIconSpe(icon_spe.value,'',latLngs[i].lat(),latLngs[i].lng());
      copyClick(newMarkers[i],originalMarker);
	  // Now we can remove the original marker safely
  	  map.removeOverlay(originalMarker);
	}
  }
  
  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      GEvent.trigger(oldMarker,'click');
    });
  }
  
  /*
  // Loop through the markers and create draggable copies
  for (var i=0; i<=_journey.getNumRoutes(); i++){
    var originalMarker = _journey.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
    map.addOverlay(newMarkers[i]);
    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragstart", function() {
        map.closeInfoWindow();  
    });
    GEvent.addListener(newMarkers[i], "dragend", function () {
      // identify which marker has been selected
	  var key=-1;
	  for(var k=0;k<newMarkers.length; k++) {
	    if ( this.ha == newMarkers[k].ha) {
		  key = k;
		}
	  }
	  var pt = newMarkers[key].getPoint();
	  map.panTo(pt);
	  geocoder.getLocations(new GLatLng(pt.lat(), pt.lng()), showAddress);
	  map.removeOverlay(newMarkers[key]);
    });
	
    // Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
	
  }
  */
  
}

function showJourney() {
  if (isset(divInfoJourney)) {
   if (_inputFieldName.length > 1) {
		if ( (document.getElementById(_inputFieldName[0]).value != '') && (document.getElementById(_inputFieldName[1] ).value != '') ) {
			if( _journey === undefined ) {
		    _journey = new GDirections(map, divInfoJourney);
		    GEvent.addListener(_journey, "addoverlay", onGDirectionsAddOverlay);
				GEvent.addListener(_journey, "load", onGDirectionsLoad); 
			} else {
			  map.clearOverlays();
  			if (document.getElementById('seeCursor').value == 'y') {
    			addSelectMarker();
  			}
			  _journey.load("");
			}
			var destination = new Array() ;
			nbCity = -1;
			for(var k=0;k<_inputFieldName.length;k++) {
			  if (k != 1) {
			    lat = document.getElementById("lat_" + _inputFieldName[k] ).value;
			    lon = document.getElementById("lon_" + _inputFieldName[k] ).value;
			    if ((lat != '') && (lon != '')) {
			      nbCity++;
			      posCity = new GLatLng(lat,lon);
		        destination[nbCity] = posCity;
						// alert(lat + '-' + lon);
			    }
			  }
			}
			k=1;
			nbCity++;
			lat = document.getElementById("lat_" + _inputFieldName[k] ).value;
			lon = document.getElementById("lon_" + _inputFieldName[k] ).value;
			posCity = new GLatLng(lat,lon);    
			destination[nbCity] = posCity; 
			if (document.getElementById('lang').value == 'FR') {
		  	  _journey.loadFromWaypoints(destination, {locale: 'fr'});
			} else if (document.getElementById('lang').value == 'UK') {
			  _journey.loadFromWaypoints(destination, {locale: 'en'});
		  } else if (_journey==undefined) {
			  _journey.load("");
			}
		}
	 } 
	}
}

// Handler de resize de la fenetre
var onResizeHandler=function(event){
  // recalcule la taille des suggestions
  setCompleteDivSize();
}

// Handler de focus sur le champ texte
var onFocusHandler=function(event){
	getField = document.getElementById(""+this.name);
  var index = - 1;
	  // definit les valeurs de current et old Input Field
	for (boucle=0; boucle<_inputFieldName.length; boucle++) {
    if ( _inputFieldName[boucle] == this.name) { index = boucle; }
  }
  valueStart = 'Etape ' + (index-1) + '...';
	// alert(valueStart);
	if (getField.value == valueStart) { getField.value = ''; }
	if (getField.value == 'Ville...') { getField.value = ''; }
	// alert(getField.value);
	cursorAfterValue(getField);
	_currentInputFieldValue[index]=this.value;
	_oldInputFieldValue[index]=_currentInputFieldValue[index];
	getLat = document.getElementById("lat_"+this.name);
	getLon = document.getElementById("lon_"+this.name);
	// positionnement de la carte Google
	if (isset(map) && getLat.value != "") {
	  setLat = getLat.value;
		setLon = getLon.value;
	  // var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(setLat, setLon), 10);
		moveCursor();
  }	
}

// Handler de blur sur le champ texte
var onBlurHandler=function(event){
  if(!_cursorUpDownPressed){
    // test coherence ville souhaitee ville selectionnee
    // force le champ ville 
	// avec le libelle complet de la ville selectionne (pays inclus)
	// l internaute peut verifier qu il a selectionne la ville souhaitee
    // si le blur n'est pas causé par la touche haut/bas
	index_field = -1;
    for(compteur=0;compteur<_inputFieldName.length;++compteur) {
        _completeDiv = document.getElementById("completeDiv_" + compteur);
        hideCompleteDiv(_completeDiv,compteur);
        if (this.id == _inputFieldName[compteur]) { index_field = compteur; }
    }
	if (this.id == 'ville_depart' || this.id == 'ville_arrivee' || this.id == 'ville_inter1' || this.id == 'ville_inter2' || this.id == 'ville_inter3' || this.id == 'ville_inter4'|| this.id == 'ville_inter5' || this.id == 'ville_inter6' || this.id == 'ville_depart_b' || this.id == 'ville_arrivee_b' || this.id == 'ville_membre' ) {  
	  // alert(this.id);
	  var nameVilleComplet = document.getElementById("nomVilleComplet_" + this.id);
	  this.value = nameVilleComplet.value;
		_oldInputFieldValue[index_field] = nameVilleComplet.value;  
		_currentInputFieldValue [index_field] = nameVilleComplet.value;  
	}
      //_submitButton.focus();
      //_lastKeyCode=-1
  }
  showJourney();
  _cursorUpDownPressed=false;
};

// declenchee quand on clique sur une div contenant une possibilite
var divOnMouseDown=function(){
  var index = - 1;
  for (ll=0; ll<_inputFieldName.length; ll++) {
    if ( _inputFieldName[ll] == _inputField.name) { index = ll; }
  }
  _inputField.value=getSuggestion(this);
  _completeDiv = document.getElementById("completeDiv_" + index);
  // recherche la position dans la liste deroulante de 
  // la ville selectionnee
  recherche = this.id;
  for (nn=0; nn<_completeDiv.childNodes.length; nn++) {
    if ( recherche == _completeDiv.childNodes[nn].id) { 
	  _highlightedSuggestionIndex[index] = nn;
	}
  }
  highlightNewValue(_highlightedSuggestionIndex[index], index);
  hideCompleteDiv(_completeDiv, index);
};

// declenchee quand on passe sur une div de possibilite. La div précédente est passee en style normal
var divOnMouseOver=function(){
  if(_highlightedSuggestionDiv) {
    setStylePourElement(_highlightedSuggestionDiv,"AutoCompleteDiv");
  }
  cherche = -1;
  for (c=0; c<_inputFieldName.length; c++) {
    if ( _inputField.name == _inputFieldName[c]) {
	  cherche = c;
	}
  }
  infoCity = this.id;
  // recuperation de la lat et long
  longitude = infoCity.substring(infoCity.lastIndexOf(" - ")+3, infoCity.length);
  infoCity = infoCity.substring(0,infoCity.lastIndexOf(" - "));
  latitude = infoCity.substring(infoCity.lastIndexOf(" - ")+3, infoCity.length);
  infoCity = infoCity.substring(0,infoCity.lastIndexOf("/"));
  
  codeGeoId = infoCity.substring(infoCity.lastIndexOf(" - ")+3, infoCity.length);
  texteVille = infoCity.substring(0,infoCity.lastIndexOf(" - "))
  storeNameOnly = document.getElementById("nameOnly_" + _inputField.name);
  storeNameOnly.value = texteVille;
  _inputField.value = this.innerHTML.replace("<span>","");
  _inputField.value = _inputField.value.replace("</span>","");
  _inputField.value = _inputField.value.replace("</SPAN>","");
  _inputField.value = _inputField.value.replace("<SPAN>","");
  storeCodeGeoId = document.getElementById("codeVille_" + _inputField.name);
  storeCodeGeoId.value = codeGeoId;
  storeCodePays = document.getElementById("code_pays_" + _inputField.name);
  getNamePays = _inputField.value.substring(_inputField.value.lastIndexOf(" - ") + 3,_inputField.value.length);
  storeCodePays.value = getInitCountry(getNamePays);
  setStylePourElement(this,"AutoCompleteDivAct");
};

// declenchee quand la sourie quitte une div de possiblite. La div repasse a l'etat normal
var divOnMouseOut = function(){
  setStylePourElement(this,"AutoCompleteDiv");
};
