/**
 * Interface API GoogleMaps
  * 17/07/2007 - 20:21
  * jlb
 */

/**
 * Déclaration des variables globales
 */


/**
 * Les textes sont stockés dans des variables pour une traduction ultérieure 
 */

/**
 * Chemin d'accès pour les URLs
 * @global string C_PATH
 */
var C_PATH = "/velovmap/";

/**
 * Textes de la bulle d'accueil
 * @global string C_TEXTE_BULLE_ACCUEIL
 */
var C_TEXTE_BULLE_ACCUEIL = "<strong>Bienvenue sur la carte V&eacute;lo'v,</strong><br><br>Double cliquez<br>sur la carte pour trouver les stations les plus proches<br> ou utilisez les onglets &agrave; gauche";

/**
 * Titre de la bulle d'accueil apparaissant en roll over sur l'icone velo'v
 * @global string C_TITRE_BULLE_ACCUEIL
 */
var C_TITRE_BULLE_ACCUEIL = "Bienvenue sur la carte V&eacute;lo'v";

/**
 * Texte affiché lors du chargement des données
 * @global string C_TEXTE_LOADING
 */
var C_TEXTE_LOADING = "Chargement en cours";

/**
 * Texte affiché dans la bulle de disponibilité
 * @global string C_TEXTE_VELOS_DISPOS
 */
var C_TEXTE_VELOS_DISPOS = "Vélos disponibles : ";

/**
 * Texte affiché dans la bulle de disponibilité
 * @global string C_TEXTE_BORNES_DISPOS
 */
var C_TEXTE_BORNES_DISPOS = "Bornes disponibles : ";

/**
 * Texte affiché dans la bulle de disponibilité
 * @C_TEXTE_NOMBRE_BORNES
 */
var C_TEXTE_NOMBRE_BORNES = "Nombre de bornes : ";


/**
 * Texte affiché si le browser n'est pas compatible Google Maps
 * @global string C_TEXTE_BROWSER_INCOMPATIBLE
 */
var C_TEXTE_BROWSER_INCOMPATIBLE = "Désolés, votre navigateur n'est pas compatible avec notre système de cartographie";


/**
 * Texte affiché si la station est fermée
 * @global string C_TEXTE_BORNE FERMEE
 */
var C_TEXTE_BORNE_FERMEE = "Station ferm&eacute;e";
/**
 *  Objet map contenant la carte
 * @global object oMap
 */
var oMap = null;

/**
 *  Objet map contenant le geocoder Google
 * @global object oGeocoder
 */
var oGeocoder = null;

/**
 *  Objet icone 'velov'
 * @global oVeloIcon
 */
oVeloIcon = new GIcon(G_DEFAULT_ICON, C_PATH + "img/iconeVelov.png" );
oVeloIcon.over = C_PATH + "img/iconeInterroge.png";
oVeloIcon.shadow = C_PATH + "img/iconeVelovOmbre.png";
oVeloIcon.shadowSize = new GSize(25, 23);
oVeloIcon.iconSize = new GSize(14, 23);	
oVeloIcon.iconAnchor = new GPoint(12, 23);

/**
 *  Objet icone 'Maison'
 * @global oHomeIcon
 */
oHomeIcon = new GIcon(G_DEFAULT_ICON, C_PATH + "img/home.png");
oHomeIcon.shadow = C_PATH + "img/homeOmbre.png";
oHomeIcon.iconSize = new GSize(32, 24);
oHomeIcon.shadowSize = new GSize(32, 24);
oHomeIcon.iconAnchor = new GPoint(16, 12);
oHomeIcon.infoWindowAnchor = new GPoint(5, 1);

/**
 *  Objet contenant les limites de la carte à afficher
 * @global oLimites
 */

//Limites carte affichée
var oLimites = null;



/**
 * fonction appellée au chargement de la page
 * Affiche la carte Google dans le div map
 */
function Start() {
	if (GBrowserIsCompatible()) {	
		/**
		 * Paramètrage de la carte
		 */
		oMapObj = document.getElementById('map');
		oMap = new GMap2(oMapObj);
		oMap.addControl(new GLargeMapControl());
		oMap.addControl(new GMapTypeControl());
		oMap.addControl(new GOverviewMapControl(new GSize(100,100)));
		oMap.disableDoubleClickZoom();
		oMap.enableContinuousZoom(); 
		oMap.enableScrollWheelZoom();
		oMap.setCenter(new GLatLng(45.75453, 4.84096), 13);
	
	
	  
		/**
		 * Création  et positionnement du layer 'chargement en cours' id = 'LoadingDiv'
		 */
		var oDiv=document.createElement("div");
		oDiv.setAttribute('id','LoadingDiv');
		oDiv.className = 'loadingDiv';
		oDiv.innerHTML = '<b>'  + C_TEXTE_LOADING + '...</b><br /><img src="' + C_PATH + 'img/loading.gif" alt="" />';
		var iLargeurMap = document.getElementById("map").clientWidth;
		var iHauteurMap = document.getElementById("map").clientHeight;
		var oPosition = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize((iLargeurMap-188)/2,(iHauteurMap-30)/2));
		oPosition.apply(oDiv);
		oMap.getContainer().appendChild(oDiv);
		
		/**
		 * ajout de la fonctionnalité double clic
		 * appel de la fonction AfficheStationsAutour
		 */
		GEvent.addListener(oMap, "dblclick", function(oMarker, oPoint) { 
													  oAccordeon.showThisHideOpen(3);
													  AfficheStationsAutour(oPoint);
													  });
		/**
		 * Création et ouverture de bulle d'accueil
		 */
		var oMarkerInfo = new GMarker(new GLatLng(45.75230565329678,4.839595556259155),{icon:oVeloIcon ,title: C_TITRE_BULLE_ACCUEIL});
		oMap.addOverlay(oMarkerInfo);
		oMarkerInfo.openInfoWindowHtml('<div style="text-align:center">' + C_TEXTE_BULLE_ACCUEIL + '</div>');
		GEvent.addListener(oMarkerInfo, "infowindowclose", function() {oMap.clearOverlays();});
		
		/**
		 * Création du géocodeur
		 */	oGeocoder = new GClientGeocoder();
	} else {
		// le navigateur n'est pas compatible Google Maps
		document.getElementById('map').innerHTML = C_TEXTE_BROWSER_INCOMPATIBLE;
	}


} // end start()



/**
 * Affiche le layer LoadingDiv en surimpression sur la carte
*/
function AfficheLoading(){
	document.getElementById('LoadingDiv').style.display="block";
}

/**
 * Masque le layer LoadingDiv en surimpression sur la carte
*/
function CacheLoading(){
	document.getElementById('LoadingDiv').style.display="none";
}


/**
 * fonction appellée lors d'un double clic sur la carte, d'un drag de l'icone maison, ou une recherche par adresse
 * Affiche l'icone maison  et les stations autour du point 
 * @param objet oPoint objet Google contenant les coordonées du point 
*/
function AfficheStationsAutour(oPoint){
	
	iNombreStation = $('nombreStation1').value;
	
	AfficheLoading();
	
	/**
	 * Efface tous les markers
	 */
	oMap.clearOverlays();

	/**
 	* ajoute et affiche un marker 'maison' à l'emplacement double cliqué
	 */
	oMarker = new GMarker(oPoint,{icon:oHomeIcon ,title:'Votre recherche', draggable:true, bouncy:true});
	oMap.addOverlay(oMarker);
	
	
	/**
 	* ajoute fonctionalité 'drag' de la maison
	 */
	GEvent.addListener(oMarker, "dragend", function() {	AfficheStationsAutour(oMarker.getPoint(),iNombreStation); });
	
	
	
	/**
 	* Extension des limites de la carte
 	*/
	oLimites = new GLatLngBounds();
	oLimites.extend(oPoint); 
	
	/**
 	* Telecharge et affiche les points trouvés
 	*/
	GDownloadUrl(C_PATH + "zhp/inc/StationsParCoord.php?lat="+oPoint.y+"&long="+oPoint.x+"&nombreStation="+iNombreStation,ChargeJson);
	
	
}

/**
 * fonction appellée pour l'affichage d'une station
 * Affiche la station
 * @param integer idstation numéro de la station
*/
function AfficheStationsParId(idstation) {
	AfficheLoading();
	oMap.clearOverlays();
	oLimites = new GLatLngBounds();
	GDownloadUrl(C_PATH + "zhp/inc/StationsParId.php?gid="+idstation, ChargeJsonSingle);
}


// affiche les markers d'un arrdt.
function AfficheStationsParArrondissement(iArrondissement) {
	AfficheLoading();
	oMap.clearOverlays();
	oLimites = new GLatLngBounds();
	GDownloadUrl(C_PATH + "zhp/inc/StationsParArrondissement.php?arrondissement="+iArrondissement, ChargeJson);
}


/**
 * Charge et affiche les markers du fichier json "zhp/inc/StationsParCoord.php"
 * Appellée par la méthode GDownloadUrl de afficheStationAutour
 */
ChargeJson = function(sDoc) {
	
	//Parse le doc JSON 
	var aJsonData = eval('(' + sDoc + ')');
	//console.log(aJsonData);

	//  Affiche les markers 
	for (var i=0; i<aJsonData.markers.length; i++) {

		var oPoint = new GLatLng(aJsonData.markers[i].x , aJsonData.markers[i].y);
		var oMarker = CreerMarker(oPoint, aJsonData.markers[i].numStation, aJsonData.markers[i].nomStation ,aJsonData.markers[i].infoStation );
	}
	
	//  determine zoome et centre sur les limites
	oMap.setZoom(oMap.getBoundsZoomLevel(oLimites));
	var clat = (oLimites.getNorthEast().lat() + oLimites.getSouthWest().lat()) /2;
	var clng = (oLimites.getNorthEast().lng() + oLimites.getSouthWest().lng()) /2;
	oMap.panTo(new GLatLng(clat,clng));
	CacheLoading();
}

/**
 * Charge et affiche le marker du fichier json "zhp/inc/StationsParId.php"
 * Appellée par la méthode GDownloadUrl
 */
ChargeJsonSingle = function(sDoc) {
	// Si les informations sont trouvées :	
	if(sDoc) {	
		//Parse le doc JSON 
		var aJsonData = eval('(' + sDoc + ')');
		var oPoint = new GLatLng(aJsonData.markers[0].x , aJsonData.markers[0].y);
		var oMarker = uniqueMarker(oPoint, aJsonData.markers[0].numStation, aJsonData.markers[0].nomStation ,aJsonData.markers[0].infoStation );
		
		//  determine zoome et centre sur les limites
		oMap.setZoom(oMap.getBoundsZoomLevel(oLimites));
		var clat = (oLimites.getNorthEast().lat() + oLimites.getSouthWest().lat()) /2;
		var clng = (oLimites.getNorthEast().lng() + oLimites.getSouthWest().lng()) /2;
		oMap.panTo(new GLatLng(clat,clng));
		CacheLoading();
	} else {
		var oPoint = oMap.getCenter();
		var oMarker = new GMarker(oPoint,{icon:oVeloIcon});
		oMap.addOverlay(oMarker);
		oMarker.openInfoWindowHtml('<p style="text-alihn:center;">Les informations de la station n\'ont pas été trouvées !</p>');
		GEvent.addListener(oMarker, "infowindowclose", function() { oMap.clearOverlays(); });
		CacheLoading();
	}
}

function uniqueMarker(oPoint,iId,sNomStation,sInfoStation) {
	var oMarkerInfo = new GMarker(oPoint,{icon:oVeloIcon ,title:sNomStation});
	sHtmlBulle = "<div style='text-align:center'><strong>" + sNomStation + "</strong><br>" + sInfoStation + "</div>";
	sHtmlBulle += "<div id='dispo' style='font-family: Verdana; font-size:10px;'><br><div align='center'>" 
						 + C_TEXTE_LOADING + "<br><br><img src='" + C_PATH + "img/loading.gif' alt='' /><br /></div><div>";
	oMap.addOverlay(oMarkerInfo);
	oMarkerInfo.openInfoWindowHtml(sHtmlBulle);
	iNocache = Math.floor(Math.random()*100000)+1;
			var request = GXmlHttp.create();
			request.open("GET", C_PATH + "zhp/inc/DispoStationsParId.php?id="+iId+"&noCache="+iNocache, true);
			request.onreadystatechange = function() {
				if (request.readyState == 4) {
				  var xmlDoc = request.responseXML;
				  sTexteDispo = '<br />';
					if (xmlDoc.getElementsByTagName('ticket')[0].firstChild.nodeValue==1){
						sTexteDispo+="<br>"+ C_TEXTE_NOMBRE_BORNES + xmlDoc.getElementsByTagName('total')[0].firstChild.nodeValue;	
						sTexteDispo+="<br>"+ C_TEXTE_VELOS_DISPOS + xmlDoc.getElementsByTagName('available')[0].firstChild.nodeValue;
						sTexteDispo+="<br>"+ C_TEXTE_BORNES_DISPOS +xmlDoc.getElementsByTagName('free')[0].firstChild.nodeValue;
					}
					else { 
						sTexteDispo+="<br/><br/>"+C_TEXTE_BORNE_FERMEE;
					} 
					document.getElementById('dispo').innerHTML = sTexteDispo;
				}
				/*else {
					setTimeout("document.getElementById('dispo').innerHTML = \"<div style='text-align:center;'><br /><br />Désolé, le service est momentanément indisponible.</div>\"", 3000);
				}*/
      }
      request.send(null);
  GEvent.addListener(oMarkerInfo, "click", function() {
			oMarkerInfo.setImage(oVeloIcon.over);
			oMarkerInfo.openInfoWindowHtml(sHtmlBulle);		  
			var request = GXmlHttp.create();
			request.open("GET", C_PATH + "zhp/inc/DispoStationsParId.php?id="+iId+"&noCache="+iNocache, true);
			request.onreadystatechange = function() {
				if (request.readyState == 4) {
				  var xmlDoc = request.responseXML;
				  sTexteDispo = '<br />';
					if (xmlDoc.getElementsByTagName('ticket')[0].firstChild.nodeValue==1){
						sTexteDispo+="<br>"+ C_TEXTE_NOMBRE_BORNES + xmlDoc.getElementsByTagName('total')[0].firstChild.nodeValue;	
						sTexteDispo+="<br>"+ C_TEXTE_VELOS_DISPOS + xmlDoc.getElementsByTagName('available')[0].firstChild.nodeValue;
						sTexteDispo+="<br>"+ C_TEXTE_BORNES_DISPOS +xmlDoc.getElementsByTagName('free')[0].firstChild.nodeValue;
					}
					else { 
						sTexteDispo+="<br/><br/>"+C_TEXTE_BORNE_FERMEE;
					} 
					document.getElementById('dispo').innerHTML = sTexteDispo;
				}
				/*else {
					setTimeout("document.getElementById('dispo').innerHTML = \"<div style='text-align:center;'><br /><br />Désolé, le service est momentanément indisponible.</div>\"", 3000);
				}*/
      }
      request.send(null);
	});
  GEvent.addListener(oMarkerInfo, 'mouseover', function() { oMarkerInfo.setImage(oVeloIcon.over); });
	GEvent.addListener(oMarkerInfo, "mouseout", function() { oMarkerInfo.setImage(oVeloIcon.image); });
	GEvent.addListener(oMarkerInfo, "infowindowclose", function() { oMarkerInfo.setImage(oVeloIcon.image); });
	oLimites.extend(oPoint); 
}

/**
 * Creation du marker Velov
 * Appellée par la fonction ChargeJson 
 * @param objet oPoint objet Google contenant les coordonées du point 
 * @param int iId identifiant unique de la station utilisé pour la requete de disponibilité
 * @param string sTitre nom de la station affiché en roll over au dessus de l'icone Velov
*/
function CreerMarker(oPoint,iId,sNomStation,sInfoStation) {
	var oMarker = new GMarker(oPoint,{icon:oVeloIcon ,title:sNomStation});
	
	GEvent.addListener(oMarker, "click", function() {
			oMarker.setImage(oVeloIcon.over);
			sHtmlBulle = "<div style='text-align:center'><strong>" + sNomStation + "</strong><br>" + sInfoStation + "</div>";
			 sHtmlBulle += "<div id='dispo' style='font-family: Verdana; font-size:10px;'><br><div align='center'>" 
					+ C_TEXTE_LOADING + "<br><br><img src='" + C_PATH + "img/loading.gif' alt='' /><br /></div><div>";
			oMarker.openInfoWindowHtml(sHtmlBulle);		  
			iNocache = Math.floor(Math.random()*100000)+1;
			var request = GXmlHttp.create();
			request.open("GET", C_PATH + "zhp/inc/DispoStationsParId.php?id="+iId+"&noCache="+iNocache, true);
			request.onreadystatechange = function() {
				if (request.readyState == 4) {
				  var xmlDoc = request.responseXML;
				  sTexteDispo = '<br />';
					if (xmlDoc.getElementsByTagName('ticket')[0].firstChild.nodeValue==1){
						sTexteDispo+="<br>"+ C_TEXTE_NOMBRE_BORNES + xmlDoc.getElementsByTagName('total')[0].firstChild.nodeValue;	
						sTexteDispo+="<br>"+ C_TEXTE_VELOS_DISPOS + xmlDoc.getElementsByTagName('available')[0].firstChild.nodeValue;
						sTexteDispo+="<br>"+ C_TEXTE_BORNES_DISPOS +xmlDoc.getElementsByTagName('free')[0].firstChild.nodeValue;
					}
					else { 
						sTexteDispo+="<br/><br/>"+C_TEXTE_BORNE_FERMEE;
					} 
					document.getElementById('dispo').innerHTML = sTexteDispo;
				}
				/*else {
					setTimeout("document.getElementById('dispo').innerHTML = \"<div style='text-align:center;'><br /><br />Désolé, le service est momentanément indisponible.</div>\"", 3000);
				}*/
      }
      request.send(null);
	});
	
	GEvent.addListener(oMarker, 'mouseover', function() { oMarker.setImage(oVeloIcon.over); });
	GEvent.addListener(oMarker, "mouseout", function() { oMarker.setImage(oVeloIcon.image); });
	GEvent.addListener(oMarker, "infowindowclose", function() { oMarker.setImage(oVeloIcon.image); });
	
	oMap.addOverlay(oMarker);
	oLimites.extend(oPoint); 
}		



/**
 * Géocodage: transforme une adresse en point Google
 * Appelle la fonction AfficheStationsAutour si réussite
 * Affiche le div 'erreurAdresse' en cas d'échec
 */
function ChercheAdresse(sAdresse) {
  if (oGeocoder) {
   oGeocoder.getLatLng(
	  sAdresse,
	  function(oPoint) {
	  if (!oPoint) {
		  $('erreurAdresse').style.display="block";
		} else {
			AfficheStationsAutour(oPoint);
		}
	  }
	);
  }
}

/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}
