//<![CDATA[
var map = null;
var geocoder = null;
var map;

//--------- exécution au chargement de la page
function init() {
   if (GBrowserIsCompatible()) {
    //geocoder
	geocoder = new GClientGeocoder();	
	}   
}

//--------- aller à l'adresses spécifiée
function showAddress(address) {
 	//-------- TRAITEMENT DE L'ADRESSE
	if (address=="") return;
	address = address+',Switzerland';
	//--------
	  if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
			document.getElementById("position").value = point;
			refreshme();
            }
          }
        );
      }
}

//--------- chargement de la carte
function initmap() {
    if (GBrowserIsCompatible()) {	
		//map
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		// get map center coordinates
		getcoord();
		// set zoom depending on radius
		if (radius==100) {startZoom = 8;}
		if (radius==50) {startZoom = 8;}
		if (radius==20) {startZoom = 10;}
		if (radius==10) {startZoom = 11;}
		if (radius==5) {startZoom = 12;}
		map.setCenter(new GLatLng(coordx, coordy), startZoom);
		//addMarker(coordx, coordy, 'centre',1);

		//draws circle
		radius=parseFloat(radius);
		coordx=parseFloat(coordx);
		coordy=parseFloat(coordy);
    	
		
		if (radius<100) drawsquare (coordx, coordy, radius); // draw sqare only if radius not default of 100
		//drawCircle(coordx, coordy, radius, "#B41221", 1, 0.75, "#0000FF",0); 

		//map.panTo(new GLatLng(coordx, coordy));
		callmap(); // call markers
    }
}

//--------- ajouter un marqueur
function addMarker(latitude, longitude, description, icontype) {

	if (icontype==1) {
		var icon1 = new GIcon(); //marqueur utilisé pour le centre
		icon1.image = "gifs/icon1.gif";        
	    icon1.shadow = "http://www.google.com/mapfiles/shadow50.png";
        icon1.iconSize = new GSize(20, 34);
        icon1.shadowSize = new GSize(37, 34);
        icon1.iconAnchor = new GPoint(9, 34);
        icon1.infoWindowAnchor = new GPoint(9, 2);
        icon1.infoShadowAnchor = new GPoint(18, 25);
		markerOptions = { icon:icon1 }; // to determine icon type
		var marker = new GMarker(new GLatLng(latitude, longitude), markerOptions);
    }
	else if (icontype==2) {
		var icon2 = new GIcon(); //marqueur utilisé pour le last minute
	   	icon2.image = "http://www.google.com/mapfiles/marker" + "L" + ".png";
	    icon2.shadow = "http://www.google.com/mapfiles/shadow50.png";
        icon2.iconSize = new GSize(20, 34);
        icon2.shadowSize = new GSize(37, 34);
        icon2.iconAnchor = new GPoint(9, 34);
        icon2.infoWindowAnchor = new GPoint(9, 2);
        icon2.infoShadowAnchor = new GPoint(18, 25);
		markerOptions = { icon:icon2 }; // to determine icon type
		var marker = new GMarker(new GLatLng(latitude, longitude), markerOptions);
    }
	else {
		var marker = new GMarker(new GLatLng(latitude, longitude));
	}
	
	GEvent.addListener(marker, 'click',
		function() {
            marker.openInfoWindowHtml(description);
        }
    );
    map.addOverlay(marker);
}
 
//--------- make asynchronous HTTP request using the XMLHttpRequest object 
function callmap()
{
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
	// get coordinates
	getcoord();
	// make call
	xmlHttp.open("GET", "Calls/GetLmMarkers.php?coordx="+coordx+"&coordy="+coordy+"&rad="+radius, true); 
	// define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse2;
    // make the server request
    xmlHttp.send(null);
  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('callprocess()', 1000);
} 


//--------- executed automatically when a message is received from the server
function handleServerResponse2() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) {
  	// status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) {
      // extract the text received
      var response = xmlHttp.responseText;
	 
	// extract first part of text with info on number of sellers
	  end=response.length;
	  pos=response.indexOf(',');
	  text=response.substr(0,pos);
	  response=response.substring(pos+1,end);
	 
	  var markers=eval("(" + response + ")");

	  	// write number of sellers
		document.getElementById("cont_submenu").innerHTML = text+' ('+markers.length+')';		
		// create markers
		for(id in markers) {
            addMarker(markers[id].latitude, markers[id].longitude, markers[id].name, markers[id].icontype);
        }

    } 
    // a HTTP status different than 200 signals an error
    else {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}
//---------- 

//code to dray  polyline
function drawsquare(coordx,coordy,radius) {

		incrx=0.008933; // constante pour incrémenter 1km de longitude
		incry=0.01305; // constante pour incrémenter 1km de latitude

		cxleft=coordx-(incrx*radius);
		cxright=coordx+(incrx*radius);		
		cytop=coordy+(incry*radius);
		cybot=coordy-(incry*radius);
		
		var polyline = new GPolyline([new GLatLng(cxleft,cytop),new GLatLng(cxright,cytop)], "#7F90C7", 4);
		map.addOverlay(polyline);
		var polyline = new GPolyline([new GLatLng(cxright,cytop),new GLatLng(cxright,cybot)], "#7F90C7", 4);
		map.addOverlay(polyline);
		var polyline = new GPolyline([new GLatLng(cxright,cybot),new GLatLng(cxleft,cybot)], "#7F90C7", 4);
		map.addOverlay(polyline);
		var polyline = new GPolyline([new GLatLng(cxleft,cybot),new GLatLng(cxleft,cytop)], "#7F90C7", 4);
		map.addOverlay(polyline);
}

/*
* Add a circle to the global variable "map". This function won't work for circles that encompass
* the North or South Pole. Also, there is a slight distortion in the upper-left, upper-right,
* lower-left, and lower-right sections of the circle that worsens as it gets larger and/or closer
* to a pole.
* @param lat Latitude in degrees
* @param lng Longitude in degrees
* @param radius Radius of the circle in statute km. 0.014483 = Convert statute miles into degrees latitude
* @param {String} strokeColor Color of the circle outline in HTML hex style, e.g. "#FF0000"
* @param strokeWidth Width of the circle outline in pixels
* @param strokeOpacity Opacity of the circle outline between 0.0 and 1.0
* @param {String} fillColor Color of the inside of the circle in HTML hex style, e.g. "#FF0000"
* @param fillOpacity Opacity of the inside of the circle between 0.0 and 1.0
*/
function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
    var d2r = Math.PI/180;
    var r2d = 180/Math.PI;
    var Clat = radius * 0.0089;  // Convert statute km into degrees latitude
    var Clng = Clat/Math.cos(lat*d2r); 
    var Cpoints = []; 
    for (var i=0; i < 65; i++) { 
      var theta = Math.PI * (i/32); 
      Cy = lat + (Clat * Math.sin(theta)); 
      Cx = lng + (Clng * Math.cos(theta)); 
      var P = new GPoint(Cx,Cy); 
      Cpoints.push(P); 
    }
    var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
    map.addOverlay(polygon);
}
