var LAST_MARKER_CH=null;
var LAST_MARKER_CH_TYPE=null;

var LAST_MARKER_GI=null;
var LAST_MARKER_GI_TYPE=null;

var MOUSE_CLICKED=null;

var MAXZ=0;

////////////////////////////////////////////////

function LatLong(degLat, degLong) {
     this.lat = LatLong.llToRad(degLat);
     this.lon = LatLong.llToRad(degLong);
   }    
   
   LatLong.llToRad = function(brng) {
     if (!isNaN(brng)) return brng * Math.PI / 180; 
   
     brng = brng.replace(/[\s]*$/,'');               
     var dir = brng.slice(-1).toUpperCase();         
     if (!/[NSEW]/.test(dir)) return NaN;           
     brng = brng.slice(0,-1);                       
     var dms = brng.split(/[\s:,Â°Âºâ€²\'â€³\"]/);         
     switch (dms.length) {                           
       case 3:                                       
         var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break;
       case 2:                                       
         var deg = dms[0]/1 + dms[1]/60; break;
       case 1:                                       
         if (/[NS]/.test(dir)) brng = '0' + brng;   
         var deg = brng.slice(0,3)/1 + brng.slice(3,5)/60 + brng.slice(5)/3600; break;
       default: return NaN;
     }
     if (/[WS]/.test(dir)) deg = -deg;               
     return deg * Math.PI / 180;                     
   }
   
   LatLong.distHaversine = function(p1, p2) {
     var R = 6371;
     var dLat  = p2.lat - p1.lat;
     var dLong = p2.lon - p1.lon;

     var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
             Math.cos(p1.lat) * Math.cos(p2.lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
     var d = R * c;
   
     return d;
   }

//////////////////////////////////////
function info_item(htmlt,id,type)
{
	
document.getElementById('infoitem').innerHTML='<img src="http://www.planete-nuit.com/img/spacer.gif" alt="Chargement" width="430" height="1" align="absmiddle"/><br><img src="http://www.planete-nuit.com/img/loading_map.gif" alt="Chargement" align="absmiddle"/>&nbsp;<span class="Style6">Chargement en cours...';
if(type=="1") var page='retrieve_data_ch_click_map.php';
if(type=="2") var page='retrieve_data_gi_click_map.php';

//requete ajax qui affiche les infos
//requete ajax
		adatafield = new Array("id");
  		adatavalue= new Array(id);
  		adata = new Array(adatafield,adatavalue);
	
		ObjAJAX = new Ajax();
		ObjAJAX.setParam ({		
		url :"http://www.planete-nuit.com/prequests/"+page,
		returnFormat : "txt", // OU returnFormat : "xml"
		method : "POST", // OU method : "GET"
		data : adata,
		//data : "mdp="+pass,
		//data : adata,
		//data :({mdp : pass,
		//		}),
		asynchronus : true,
		onComplete : "document.getElementById('infoitem').innerHTML=response;"
		
	
		});
		ObjAJAX.execute();
	
}

function info_item_p(htmlt,id,type)
{
	//alert(id);
document.getElementById('infoitem').innerHTML='<img src="http://www.planete-nuit.com/img/spacer.gif" alt="Chargement" width="430" height="1" align="absmiddle"/><br><img src="http://www.planete-nuit.com/img/loading_map.gif" alt="Chargement" align="absmiddle"/>&nbsp;<span class="Style6">Chargement en cours...';

if(type=="11") var page='retrieve_data_ch_click_map_p.php';
if(type=="22") var page='retrieve_data_gi_click_map_p.php';

//requete ajax qui affiche les infos
//requete ajax
		adatafield = new Array("id");
  		adatavalue= new Array(id);
  		adata = new Array(adatafield,adatavalue);
	
		ObjAJAX = new Ajax();
		ObjAJAX.setParam ({
		url : "http://www.planete-nuit.com/prequests/"+page,
		returnFormat : "txt", // OU returnFormat : "xml"
		method : "POST", // OU method : "GET"
		data : adata,
		//data : "mdp="+pass,
		//data : adata,
		//data :({mdp : pass,
		//		}),
		asynchronus : true,
		onComplete : "document.getElementById('infoitem').innerHTML=response;"
		
	
		});
		ObjAJAX.execute();
	
}

function pretty(a,b) {
        return '<table border="0" cellpadding="0" cellspacing="0"><tr><td width="100%" class="EWTitle" nowrap>' + a +
               '<a href="javascript:ewindow.hide()"><img title="Fermer" src="http://www.planete-nuit.com/img/eclose.png" border=0 style="position:absolute;right:4px;top:4px"></a>' +
               '</td></tr>' +
               '<tr><td nowrap>' + b + '</td></tr></table>';
      }

var icon_1 = new GIcon();
icon_1.image = "http://www.planete-nuit.com/img/ch2.png";
icon_1.iconSize = new GSize(14, 16);
icon_1.iconAnchor = new GPoint(7, 8);
icon_1.infoWindowAnchor = new GPoint(7, 8);

var icon_11 = new GIcon();
icon_11.image = "http://www.planete-nuit.com/img/ch2p.png";
icon_11.iconSize = new GSize(14, 16);
icon_11.iconAnchor = new GPoint(7, 8);
icon_11.infoWindowAnchor = new GPoint(7, 8);

var icon_2 = new GIcon();
icon_2.image = "http://www.planete-nuit.com/img/gi2.png";
icon_2.iconSize = new GSize(14, 16);
icon_2.iconAnchor = new GPoint(12, 12);
icon_2.infoWindowAnchor = new GPoint(12, 12);

var icon_22 = new GIcon();
icon_22.image = "http://www.planete-nuit.com/img/gi2p.png";
icon_22.iconSize = new GSize(14, 16);
icon_22.iconAnchor = new GPoint(12, 12);
icon_22.infoWindowAnchor = new GPoint(12, 12);

var icon_prefecture = new GIcon();
icon_prefecture.image = "http://www.planete-nuit.com/img/pref.png";
icon_prefecture.iconSize = new GSize(10, 10);
icon_prefecture.iconAnchor = new GPoint(5, 5);
icon_prefecture.infoWindowAnchor = new GPoint(5, 5);

var map;
function myzoom(a) {
	a > 0 ? map.zoomIn('', false, true): map.zoomOut('', true);
}

function mymove(a,b) {
	map.panDirection(a,b);
}

function affiche_marker(i) {
	map.panTo(aMarkers[i].getPoint());
	//aMarkers[i].openInfoWindowHtml(aMarkersHtml[i]);
	aMarkers[i].setImage(icon_ville1.image);
}

function affiche_marker2(i) {
	map.panTo(aMarkers[i].getPoint());
	//aMarkers[i].openInfoWindowHtml(aMarkersHtml[i]);
}

function revert_marker(i) {
	aMarkers[i].setImage(icon_annonce.image);
}

function wheelZoom(a) {
	if (!a) a = window.event; 
	if (a.preventDefault) a.preventDefault(); 
	a.returnValue = false; 

	//if(a.cancelable){
	//	a.preventDefault();
	//}
	//(a.detail || -a.wheelDelta) < 0 ? map.zoomIn('', false, true): map.zoomOut('', true);
	//return false;
}

function changeType(a){
	if(a=='satellite'){
		map.setMapType(G_SATELLITE_TYPE);
	}

	if(a=='map'){
		map.setMapType(G_MAP_TYPE);
	}

	if(a=='hybrid'){
		map.setMapType(G_HYBRID_MAP);
	}
}


function createMarker(point, contenu_html, vide, index_gg, type_icon,id,type) {

var marker = new PdMarker(point, type_icon);

//CLICK

GEvent.addListener(marker, "click", function() {
		
	
		
		
	
		
		if(LAST_MARKER_CH) {
		LAST_MARKER_CH.blink(false,500);
		if(LAST_MARKER_CH_TYPE=="11")
		{ 
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/ch2p.png"); 
		}
		else
		{ 
		
		if(LAST_MARKER_CH_TYPE=="1")
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/ch2.png");
		
		if(LAST_MARKER_CH_TYPE=="2")
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/gi2.png");
		
		if(LAST_MARKER_CH_TYPE=="22")
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/gi2p.png");
		
		
		}
		
		}
		
		
		MOUSE_CLICKED=marker;
		
		marker.blink(true,500);
		
		
		
		if(type=="1")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch-e.png");
		 info_item(contenu_html,id,type);
		}
		
		if(type=="11")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch2p-e2.png");
		info_item_p(contenu_html,id,type);
		}
		
		if(type=="2")
		{
		marker.setImage("http://www.planete-nuit.com/img/gi-e.png");
		 info_item(contenu_html,id,type);
		}
		
		if(type=="22")
		{
		marker.setImage("http://www.planete-nuit.com/img/gi2p-e2.png");
		info_item_p(contenu_html,id,type);
		}
		
		
		
		LAST_MARKER_CH=marker;
		LAST_MARKER_CH_TYPE=type;
		
		
		
		
		
		
		
		
		
		});
		
//MOUSE OUT
GEvent.addListener(marker, "mouseout", function() {

if(MOUSE_CLICKED!=marker)
	{
	

		if(type=="11")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch2p.png");
		}
		if(type=="1")
		{ 
		marker.setImage("http://www.planete-nuit.com/img/ch2.png"); 
		}
		
		if(type=="22")
		{
		marker.setImage("http://www.planete-nuit.com/img/gi2p.png");
		}
		if(type=="2")
		{ 
		marker.setImage("http://www.planete-nuit.com/img/gi2.png"); 
		}
		
	
	
	}
		
});		

//MOUSE OVER
	GEvent.addListener(marker, "mouseover", function() {
	
	if(MOUSE_CLICKED!=marker)
	{

		if(type=="11")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch2p-e.png");
		}
		if(type=="1")
		{ 
		marker.setImage("http://www.planete-nuit.com/img/mo.png"); 
		}
		
		if(type=="22")
		{
		marker.setImage("http://www.planete-nuit.com/img/gi2p-e.png");
		}
		if(type=="2")
		{ 
		marker.setImage("http://www.planete-nuit.com/img/mog.png"); 
		}
		
		
	}




	
	});


//properties of markers


	marker.setTooltip(contenu_html);
	/*
//images de mouse over
if(type=="11")
marker.setHoverImage("http://www.planete-nuit.com/img/ch2p-e.png");
if(type=="1")
marker.setHoverImage("http://www.planete-nuit.com/img/mo.png");*/



		
		


		
		
	/*	
		MOUSE_CLICKED=marker;
	
		
		if(LAST_MARKER_CH) {
		if(LAST_MARKER_CH_TYPE=="11")
		{ 
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/ch2p.png"); 
		}
		else
		{ 
		LAST_MARKER_CH.setImage("http://www.planete-nuit.com/img/ch2.png");
		}
		
		}
		
		
		//ewindow.openOnMarker(marker,pretty('',contenu_html))
		if(type=="1")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch-e.png");
		}
		
		if(type=="11")
		{
		marker.setImage("http://www.planete-nuit.com/img/ch2p-e2.png");
		}
		
		
		
		var LAST_MARKER_CH=marker;
		var LAST_MARKER_CH_TYPE=type;
		
		if(type=="11")
		{
			info_item_p(contenu_html,id);
		}
		if(type=="1")
		{ info_item(contenu_html,id); }
		
		
		
		*/
		
		
		












	

	
	return marker;
	

}


function createMarkerp(point, contenu_html, vide, index_gg, type_icon) {
	var marker = new GMarker(point, type_icon);
	/*GEvent.addListener(marker, "mouseover", function() {
		marker.openInfoWindowHtml(contenu_html);
	});*/
	return marker;
}

function createMarker2(point, contenu_html, vide, index_gg, type_icon) {
	var marker = new GMarker(point, type_icon);
	GEvent.addListener(marker, "click", function() {
	//	marker.openInfoWindowHtml(contenu_html);
	});
	aMarkers[index_gg] = marker;
	aMarkersHtml[index_gg] = contenu_html;
	return marker;
}
var aMarkers = new Array();
var aMarkersHtml = new Array();

function createDragMarker(point, contenu_html, vide, index_gg, type_icon) {
	var marker = new GMarker(point, {draggable: true});
	GEvent.addListener(marker, "click", function() {
		//marker.openInfoWindowHtml(contenu_html);
	});
	return marker;
}

	  
	   function process_it(doc) {
	   // alert(doc);
	   var lat=null;
	   var lng=null;
        // === split the document into lines ===
        lines = doc.split("#");
        for (var i=0; i<lines.length; i++) {
          if (lines[i].length > 1) {
            // === split each line into parts separated by "|" and use the contents ===
            parts = lines[i].split("|");
			
			
			//on stocke l'ancien point si celui-ci avait un type = 11 (plusieurs ch)
			//if(type=="11") //nous sommes dans une boucle donc la nouvelle valeur n'est pas encore defini
		/*	if(lat) //nous sommes dans une boucle donc la nouvelle valeur n'est pas encore defini
			{
				
				 startPoint = new LatLong(lat, lng); //ancien point
				  endPoint = new LatLong(parseFloat(parts[0]), parseFloat(parts[1])); //nouveau point
				  var dist = LatLong.distHaversine(startPoint, endPoint); // exprimé en Km. 
				  
				//on stocke la distance
			
			}
			else
			var dist=0;
			*/
			
			
            var lat = parseFloat(parts[0]);
            var lng = parseFloat(parts[1]);
            var html = parts[2];
            var label = parts[3];
			var id_item = parts[5];
			
			//on force le type si distance inferieur à 15km et si distance existe
			/*if(dist<15 && dist>0) 
			{ 
			var type=="11"; 
			}
			else
			{ 
			var type = parts[4]; 
			}*/
			var type = parts[4];
			var point = new GLatLng(lat,lng);
            // create the marker
            //var marker = createMarker(point,label,html);
			
			//ici on affiche le marqueur uniquement si la distance est supérieur à 15 km
			/*if(dist>15)
			{*/
			var marker = createMarker(point,label,"", label, eval('icon_'+type),id_item,type);
			//alert(GOverlay.getZIndex(marker.getPoint().lat()));
			/*if(abs(GOverlay.getZIndex(marker.getPoint().lat()))>=MAXZ)
			MAXZ=GOverlay.getZIndex(marker.getPoint().lat());*/
            map.addOverlay(marker);
			/*}*/
			//sinon on continue la boucle...
          }
        }
        // put the assembled side_bar_html contents into the side_bar div
        //document.getElementById("side_bar").innerHTML = side_bar_html;
      }  
//alert(MAXZ);	  
/////////////////////////////////////////////////////////////
   // ====== Create a Client Geocoder ======
      var geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
	 
      // ====== Geocoding ======
      function showAddress(ss,name,afficher_pref_non) {
        var search = ss;
		//alert(afficher_pref_non);
		var afficher_pref_nontwo=afficher_pref_non;
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
		  //alert(afficher_pref_nontwo);
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              //document.getElementById("message").innerHTML = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;
                //var marker = new GMarker(new GLatLng(p[1],p[0]));
                //document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
				//alert(afficher_pref_nontwo);
				if(afficher_pref_nontwo==0)
				{
				var marker=createMarkerp(new GLatLng(p[1],p[0]),'',"", name, icon_prefecture);
                map.addOverlay(marker);
				//label
				//var label = new ELabel(new GLatLng(p[1],p[0]), name.replace(" ","&nbsp;"), "prefecture_name");
				//map.addOverlay(label);
				}
              }
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
			  if(afficher_pref_nontwo==0)
              map.setCenter(new GLatLng(p[1],p[0]),8);
			  else
			  map.setCenter(new GLatLng(p[1],p[0]),6);
			  
			  
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              // alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }
    

////////////////////////////////////////////////////////////////////////////////////////// 
