/**
 * Interface API GoogleMaps
 * 19/11/2009 - 15:21
 * rfr
 */

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

/**
 * Chemin d'accès pour les URLs
 * @global string C_PATH
 */
var C_PATH = "/typo3conf/ext/gl_clusnet_carto/pi1/";

/**
 * Chemin d'accès pour les Images
 * @global string C_IMGPATH
 */
var C_IMGPATH = "/typo3conf/ext/gl_clusnet_carto/pi1/res/img/";

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

/**
 * Texte affiché si le browser n'est pas compatible Google Maps
 * @global string C_TEXTE_BROWSER_INCOMPATIBLE
 */
var C_TEXTE_BROWSER_INCOMPATIBLE = "Sorry, your web browser is not supported !";


var C_SINGLE_URL = "";
/**
 *  Objet map contenant la carte
 * @global object oMap
 */
var oMap = null;

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

/**
 *  Objet icone 'cluster'
 * @global oClusterIcon
 */
oClusterIcon = new GIcon(G_DEFAULT_ICON, C_IMGPATH + "iconCluster.png" );
oClusterIcon.over = C_IMGPATH + "iconOver.png";
oClusterIcon.clicked = C_IMGPATH + "iconClick.png";
oClusterIcon.shadow = C_IMGPATH + "iconClusterShadow.png";
oClusterIcon.shadowSize = new GSize(0, 0);
oClusterIcon.iconSize = new GSize(15, 15);	
oClusterIcon.iconAnchor = new GPoint(7, 7);

/**
 *  Objet icone 'cluster selectionne'
 * @global oSelectedIcon
 */
oSelectedIcon = new GIcon(G_DEFAULT_ICON, C_IMGPATH + "iconClick.png" );
oSelectedIcon.shadowSize = new GSize(0, 0);
oSelectedIcon.iconSize = new GSize(15, 15);	
oSelectedIcon.iconAnchor = new GPoint(7, 7);

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

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

// Type de cartes (plan, sattelite, mixte, ...)
var mT = 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(48.661943, 12.964844), 4);
		mT = oMap.getMapTypes();
		for (var i=0; i < mT.length; i++) { 
			mT[i].getMinimumResolution = function() { return 4; };
			mT[i].getMaximumResolution = function() { return 17; };
		}
		  
		/**
		 * 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 = '<strong>'  + C_TEXTE_LOADING + '...</strong><br /><img src="' + C_IMGPATH + '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é clic
		 * appel de la fonction AfficheClusters
		 */
		/*GEvent.addListener(oMap, "click", function(oMarker, oPoint) { 
													  oAccordeon.showThisHideOpen(2);
													  AfficheClusters(oPoint);
												  });*/
		GEvent.addListener(oMap, "infowindowclose", function() {
			if(oSelectedMarker) {
				oMap.removeOverlay(oSelectedMarker);
				oSelectedMarker = null;
			}
		});
		
		/**
		 * 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";
}

/******************************************************************************/

function initialize() {
	document.getElementById('selectCountry').selectedIndex = -1;
	document.getElementById('selectCity').selectedIndex = -1;
	document.getElementById('selectTheme').selectedIndex = -1;
	
	displayAllClusters();
}

/**
 * fonction appellée lors du chargement de la carte, affichage de tous les clusters actifs
*/
function displayAllClusters() {
	
	// Affiche le bloc de "Chargement"
	AfficheLoading();

	oMap.clearOverlays(); /* Efface tous les markers */
	oLimites = null;
	
	/* Telecharge et affiche les points trouvés */
	GDownloadUrl(C_PATH + "zhp/inc/displayAllClusters.php", ChargeJson);	
}

/**
 * fonction appellée pour l'affichage d'un cluster
 * Affiche le cluster
 * @param integer idcluster identifiant du cluster
*/
function displayClusterById(idcluster) {
	AfficheLoading();
	oMap.clearOverlays();
	oLimites = new GLatLngBounds();
	GDownloadUrl(C_PATH + "zhp/inc/displayClusterById.php?gid="+idcluster, ChargeJsonSingle);
}

/**
 * fonction appellee pour l'affichage des clusters d'un themes selectionne
 * Affiche les clusters
 * @param integer idcluster identifiant du theme
*/
function displayClusterByTheme(idtheme) {
	AfficheLoading();
	document.getElementById('selectCountry').selectedIndex = -1;
	document.getElementById('selectCity').selectedIndex = -1;
	oMap.clearOverlays();
	oLimites = new GLatLngBounds();
	GDownloadUrl(C_PATH + "zhp/inc/displayClustersByTheme.php?id="+idtheme, ChargeJsonTheme);
}

/**
 * fonction appellee pour l'affichage des clusters d'un themes selectionne
 * Affiche les clusters
 * @param integer idzone identifiant de la ville (zone)
*/
function displayClusterByZone(idzone) {
	AfficheLoading();
	document.getElementById('selectCountry').selectedIndex = -1;
	document.getElementById('selectTheme').selectedIndex = -1;
	oMap.clearOverlays();
	GDownloadUrl(C_PATH + "zhp/inc/displayClustersByZone.php?id="+idzone, ChargeJsonZone);
}

/**
 * fonction appellee pour l'affichage des clusters d'un pays selectionne
 * Affiche les clusters
 * @param integer idcountry identifiant du pays
*/
function displayClusterByCountry(idcountry) {
	AfficheLoading();
	document.getElementById('selectTheme').selectedIndex = -1;
	document.getElementById('selectCity').selectedIndex = -1;
	oMap.clearOverlays();
	GDownloadUrl(C_PATH + "zhp/inc/displayClustersByCountry.php?id="+idcountry, ChargeJsonCountry);
}

/******************************************************************************/
/**
 * Charge et affiche les markers du fichier json "zhp/inc/displayAllClusters.php"
 * Appellée par la méthode GDownloadUrl de displayAllClusters
 */
ChargeJson = function(sDoc) {

	// La requête a renvoyé un résultat
	if(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, oClusterIcon, aJsonData.markers[i]);
		}
		
		if(oLimites) {
			//  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));
		} else {
			oMap.setCenter(new GLatLng(48.661943, 12.964844), 4);
		}
		CacheLoading();
	}
	else {
		CacheLoading();
	}
}

/**
 * Charge et affiche les markers du fichier json "zhp/inc/displayAllClusters.php"
 * Appellée par la méthode GDownloadUrl de displayAllClusters
 */
ChargeJsonTheme = function(sDoc) {

	// La requête a renvoyé un résultat
	if(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, oClusterIcon, aJsonData.markers[i]);
		}

		if(document.getElementById('selectTheme').selectedIndex == 0) {
			oMap.setCenter(new GLatLng(48.661943, 12.964844), 4);
		} else if(oLimites) {
			//  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));
		} else {
			oMap.setCenter(new GLatLng(48.661943, 12.964844), 4);
		}
		CacheLoading();
	}
	else {
		CacheLoading();
	}
}

/**
 * Charge et affiche le marker du fichier json "zhp/inc/ClusterParId.php"
 * Appellée par la méthode GDownloadUrl
 */
ChargeJsonSingle = function(sDoc) {

	if(sDoc != '') {
		//Parse le doc JSON 
		var aJsonData = eval('(' + sDoc + ')');
		var oPoint = new GLatLng(aJsonData.markers[0].x , aJsonData.markers[0].y);
		var oMarker = CreerMarker(oPoint, oClusterIcon, aJsonData.markers[0]);
		oMarker.openInfoWindowHtml('');
	
		//  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:oClusterIcon});
		oMap.addOverlay(oMarker);
		oMarker.openInfoWindowHtml('<p style="text-align:center;">Sorry,<br/><br />Your request did not succeed !</p>');
		GEvent.addListener(oMarker, "infowindowclose", function() { oMap.clearOverlays(); });
		CacheLoading();
	}
}

/**
 * Charge et affiche les markers du fichier json "zhp/inc/displayClustersByZone.php"
 * Appellée par la méthode GDownloadUrl de displayClustersByZone
 */
ChargeJsonZone = function(sDoc) {

	// La requête a renvoyé un résultat
	if(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, oClusterIcon, aJsonData.markers[i]);
		}
		oMap.setCenter(new GLatLng(aJsonData.markers[0].zone_x , aJsonData.markers[0].zone_y), aJsonData.markers[0].zone_zoom);
		CacheLoading();
	}
	else {
		CacheLoading();
	}
}

/**
 * Charge et affiche les markers du fichier json "zhp/inc/displayClustersByCountry.php"
 * Appellée par la méthode GDownloadUrl de displayClustersByCountry
 */
ChargeJsonCountry = function(sDoc) {

	// La requête a renvoyé un résultat
	if(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, oClusterIcon, aJsonData.markers[i]);
		}
		oMap.setCenter(new GLatLng(aJsonData.markers[0].country_x , aJsonData.markers[0].country_y), aJsonData.markers[0].country_zoom);
		CacheLoading();
	} else if(document.getElementById('selectCountry').value > 0) {
		GDownloadUrl(C_PATH + "zhp/inc/noCountry.php?id="+document.getElementById('selectCountry').value, ChargeJsonError);
	} else {
		CacheLoading();
	}
}

ChargeJsonError = function(sDoc) {

	// La requête a renvoyé un résultat
	if(sDoc != '') {
		//Parse le doc JSON 
		var aJsonData = eval('(' + sDoc + ')');
		oMap.setCenter(new GLatLng(aJsonData.markers[0].error_x , aJsonData.markers[0].error_y), aJsonData.markers[0].error_zoom);
		CacheLoading();
	} else {
		CacheLoading();
	}
}

/******************************************************************************/
/**
 * Creation du marker Cluster
 * Appellée par la fonction ChargeJson 
 * @param objet oPoint objet Google contenant les coordonees du point 
 * @param int iId identifiant unique du cluster
 * @param array sInfo informations sur le cluster
*/
function CreerMarker(oPoint, oIcon, sInfo) {
	
	var oMarker = new GMarker(oPoint,{icon:oIcon ,title:"Click for more details"});
	GEvent.addListener(oMarker, "click", function() {
		if(oMap.getZoom() >= sInfo.zone_zoom) {
			oSelectedMarker = oMarker;
			
			sHtmlBulle = "<div class=\"infoBulle\">";
			if(escape(sInfo.logo) != '')
				sHtmlBulle += "<div class=\"clusterLogo\"><img src=\""+sInfo.logo+"\" width=\"75\" title=\""+sInfo.title+"\" /></div>";
			sHtmlBulle += "<div class=\"clusterName\">"+sInfo.title+"</div>";
			if(escape(sInfo.theme) != '')
				sHtmlBulle += "<div class=\"clusterTheme\">"+sInfo.theme+"</div>";
			sHtmlBulle += "<div class=\"clusterInfos\">";
			if(escape(sInfo.website) != '')
				sHtmlBulle += "<div class=\"clusterSite\"><span class=\"clusterLinkLabel\">Website:</span>&nbsp;<a href=\""+sInfo.websiteURL+"\" target=\"_blank\" title=\"Go to the "+sInfo.title+" website (new window)\">"+sInfo.websiteLabel+"</a></div>";
			if(escape(sInfo.cemail) != '')
				sHtmlBulle += "<div class=\"clusterSite\"><span class=\"clusterLinkLabel\">Contact:</span>&nbsp;<a href=\""+sInfo.cemail+"\" target=\"_blank\" title=\"Contact "+sInfo.contact+"\">"+sInfo.contact+"</a></div>";
			sHtmlBulle += "</div>";
			sHtmlBulle += "<div class=\"clusterDetails\"><a href=\"" + C_SINGLE_URL + sInfo.link + "\" onclick=\"window.open('" + C_SINGLE_URL + sInfo.link + "','details','(resizable=yes,toolbar=no,scrollbars=yes,menubar=yes,width=800px,height=600px)');return false;\" targer=\"_blank\">More details</a></div>";
			sHtmlBulle += "</div>";

			oMarker.openInfoWindowHtml(sHtmlBulle);		  
			iNocache = Math.floor(Math.random()*100000)+1;
			oMarker.setImage(oIcon.clicked);
		
		} else if(oMap.getZoom() < sInfo.country_zoom) {
			// Gestion du menu
			if(oAccordeon.previousClick == 4)
				oAccordeon.showThisHideOpen(3);

			oMap.setCenter(new GLatLng(sInfo.country_x , sInfo.country_y), sInfo.country_zoom);
		} else {
			// Gestion du menu
			if(oAccordeon.previousClick == 4)
				oAccordeon.showThisHideOpen(3);

			oMap.setCenter(new GLatLng(sInfo.zone_x , sInfo.zone_y), sInfo.zone_zoom);
		}
	});
	
	GEvent.addListener(oMarker, 'mouseover', function() {
		if(oMap.getZoom() >= sInfo.zone_zoom && !oSelectedMarker)
			oMarker.setImage(oIcon.over);
	});
	GEvent.addListener(oMarker, "mouseout", function() { 
		if(oMap.getZoom() >= sInfo.zone_zoom && !oSelectedMarker)
			oMarker.setImage(oIcon.image);
	});
	GEvent.addListener(oMarker, "infowindowclose", function() {
		oMarker.setImage(oIcon.image);
		oSelectedMarker = null;
	});
	
	if(oLimites)
		oLimites.extend(oPoint);
	
	oMap.addOverlay(oMarker);
	
	return oMarker;
}

/******************************************************************************/
/* 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
}