// Nombre de cercle maximum à afficher dans la carte
var nbCircleMax = 3;

// Rayon initial des cercles à la création en m
var  rayonInitial = 2500;

var infoOpen = true;
var myMap = null;
var myQueryControl = null;

var geocodeur = new GClientGeocoder();


function rechercheAdresse(){
	var adresse = document.getElementById('champRechercheAdresse').value;

	
	geocodeur.getLatLng(adresse, function(point){
			
			if( point==null){
				alert('Adresse non trouvée');
			} else {
				myMap.setCenter(point, 12);
			}
										
	});
}




// Affichage/ Masquage de l'overlay d'information
function closeInfo(){
	var divInfo = document.getElementById('infoMap');

	if (infoOpen){
		
	divInfo.style.width='25px';
	divInfo.style.height='30px';
	divInfo.style.backgroundColor='transparent';
	divInfo.style.border='none';
	
	} else {
				
	divInfo.style.width='400px';
	divInfo.style.height='250px';
	divInfo.style.backgroundColor='#ededed';
	divInfo.style.border='1px solid black';	
	}
	infoOpen = !infoOpen;
	
}


// Met à jour les champs du formulaire avec les données des cercles
function updateForm(){
	for ( i= 0 ; i<myQueryControl._geoQueries.length ; i++){
		j = (i+1).toString();
		document.getElementById('rayon'+j).value=myQueryControl._geoQueries[i]._radius;
		document.getElementById('lat'+j).value=myQueryControl._geoQueries[i]._centerHandle.getLatLng().lat();
		document.getElementById('lon'+j).value=myQueryControl._geoQueries[i]._centerHandle.getLatLng().lng();
	}
	for ( k= i ; k<3 ; k++){
		j = (k+1).toString();
		document.getElementById('rayon'+j).value=0;
		document.getElementById('lat'+j).value=0;
		document.getElementById('lon'+j).value=0;
	}
}


// fonction lancée automatiquement après le chargement des scripts Google (sur page depot d'annonce)
function displayMap(){
  myMap = new GMap2(document.getElementById("map"));
  
  //Centrage de la carte
  myMap.setCenter(new GLatLng(43.5,5.526123), 8);
  myMap.addControl(new GLargeMapControl3D());
  myMap.addControl(new GMapTypeControl());
  myMap.disableDoubleClickZoom();

	// affichage du calque 'zones de recherche'
   myQueryControl = new QueryControl();
   myMap.addControl(myQueryControl);
   
  
	// affichage de l'orverlay d'info
	myMap.addControl(new overlayInfo);
	
	
	// affichage du champ de recherche
	myMap.addControl(new overlayRecherche);
  
	//ajout de la détection du clic sur la carte pour création du cercle
  GEvent.addListener(myMap, "dblclick", function(overlay, point) {
    if (point) {
      singleClick = !singleClick;
		if (singleClick && (myQueryControl.getNbCircle() < nbCircleMax)) {
				setTimeout(function(){
					createCircle(new GLatLng(point.y ,point.x ), rayonInitial);
				},200);
			}
   
		if (singleClick && (myQueryControl.getNbCircle() >=nbCircleMax)) {
				setTimeout(function(){
					alert("Vous ne pouvez pas créer plus de "+nbCircleMax+" zones de recherche");
				},200);
			}
    }
	
  });
  
  
}


// fonction lancée automatiquement après le chargement des scripts Google sur la page update
function displayMapEditable(){
  myMap = new GMap2(document.getElementById("map"));
  
  //Centrage de la carte
  myMap.setCenter(new GLatLng(43.5,5.526123), 8);
  myMap.addControl(new GLargeMapControl3D());
  myMap.addControl(new GMapTypeControl());
  myMap.disableDoubleClickZoom();

	// affichage du calque 'zones de recherche'
   myQueryControl = new QueryControl();
   myMap.addControl(myQueryControl);
   

   
  // Création des cercles existants
  for( var i=0; i < arrayCercles.length ; i++){
  	createCircle(new GLatLng(arrayCercles[i].lat, arrayCercles[i].lon), arrayCercles[i].rayon);
	
		//centre la carte sur les limites
	var clat = (myQueryControl.limites.getNorthEast().lat() + myQueryControl.limites.getSouthWest().lat()) /2;
	var clng = (myQueryControl.limites.getNorthEast().lng() + myQueryControl.limites.getSouthWest().lng()) /2;
	myMap.panTo(new GLatLng(clat,clng));
	myMap.setZoom(myMap.getBoundsZoomLevel(myQueryControl.limites)-1);
  }
  updateForm();
	//ajout de la détection du clic sur la carte pour création du cercle
  GEvent.addListener(myMap, "dblclick", function(overlay, point) {
    if (point) {
      singleClick = !singleClick;
		if (singleClick && (myQueryControl.getNbCircle() < nbCircleMax)) {
				setTimeout(function(){
					createCircle(new GLatLng(point.y ,point.x ), rayonInitial);
				},200);
			}
   
		if (singleClick && (myQueryControl.getNbCircle() >=nbCircleMax)) {
				setTimeout(function(){
					alert("Vous ne pouvez pas créer plus de "+nbCircleMax+" zones de recherche");
				},200);
			}
    }
	
  });
  
  
}



// controle de l'overlay d'information
// Prend le div 'infoMap' de la page html et l'affichge dans la carte
function overlayInfo(){}
  
overlayInfo.prototype = new GControl();

overlayInfo.prototype.initialize = function(myMap){
	var divInfo = document.getElementById('infoMap');
	divInfo.style.display ='';
	myMap.getContainer().appendChild(divInfo);
	return (divInfo);
 }

// Position de l'overlay d'information
overlayInfo.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
}

// controle de l'overlay de recherche
// Prend le div 'rechercheAdresse' de la page html et l'affichge dans la carte
function overlayRecherche(){}
  
overlayRecherche.prototype = new GControl();

overlayRecherche.prototype.initialize = function(myMap){
	var divInfo = document.getElementById('rechercheAdresse');
	myMap.getContainer().appendChild(divInfo);
	return (divInfo);
 }

// Position de l'overlay d'information
overlayRecherche.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 340));
}




var metric = true;
var singleClick = false;
var queryCenterOptions = new Object();
var queryLineOptions = new Object();

queryCenterOptions.icon = new GIcon();
queryCenterOptions.icon.image = "http://www.acqsion.com/img/centerArrow.png";
queryCenterOptions.icon.iconSize = new GSize(29,22);
queryCenterOptions.icon.shadowSize = new GSize(0, 0);
queryCenterOptions.icon.iconAnchor = new GPoint(10, 10);
queryCenterOptions.draggable = true;
queryCenterOptions.bouncy = true;

queryLineOptions.icon = new GIcon();
queryLineOptions.icon.image = "http://www.acqsion.com/img/resizeArrow.png";
queryLineOptions.icon.iconSize = new GSize(20,20);
queryLineOptions.icon.shadowSize = new GSize(0, 0);
queryLineOptions.icon.iconAnchor = new GPoint(10, 10);
queryLineOptions.draggable = true;
queryLineOptions.bouncy = true;

function createCircle(point, radius) {

  singleClick = false;
  geoQuery = new GeoQuery();
  geoQuery.initializeCircle(radius, point, myMap);
  myQueryControl.addGeoQuery(geoQuery);
  geoQuery.render();
  myQueryControl.limites = geoQuery.limites;

}

function destination(orig, hdng, dist) {
  var R = 6371; // earth's mean radius in km
  var oX, oY;
  var x, y;
  var d = dist/R;  // d = angular distance covered on earth's surface
  hdng = hdng * Math.PI / 180; // degrees to radians
  oX = orig.x * Math.PI / 180;
  oY = orig.y * Math.PI / 180;

  y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
  x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));

  y = y * 180 / Math.PI;
  x = x * 180 / Math.PI;
  return new GLatLng(y, x);
}

function distance(point1, point2) {
  var R = 6371; // earth's mean radius in km
  var lon1 = point1.lng()* Math.PI / 180;
  var lat1 = point1.lat() * Math.PI / 180;
  var lon2 = point2.lng() * Math.PI / 180;
  var lat2 = point2.lat() * Math.PI / 180;

  var deltaLat = lat1 - lat2
  var deltaLon = lon1 - lon2

  var step1 = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin(deltaLon/2), 2);
  var step2 = 2 * Math.atan2(Math.sqrt(step1), Math.sqrt(1 - step1));
  return step2 * R;
}

function GeoQuery() {

}

GeoQuery.prototype.CIRCLE='circle';
GeoQuery.prototype.COLORS=["#0000ff", "#00ff00", "#ff0000"];
var COLORI=0;
GeoQuery.prototype.limites = new GLatLngBounds();

GeoQuery.prototype = new GeoQuery();
GeoQuery.prototype._map;
GeoQuery.prototype._type;
GeoQuery.prototype._radius;
GeoQuery.prototype._dragHandle;
GeoQuery.prototype._centerHandle;
GeoQuery.prototype._polyline;
GeoQuery.prototype._color ;
GeoQuery.prototype._control;
GeoQuery.prototype._points;
GeoQuery.prototype._dragHandlePosition;
GeoQuery.prototype._centerHandlePosition;



GeoQuery.prototype.initializeCircle = function(radius, point, map) {
	

	
    this._type = this.CIRCLE;
    this._radius = radius;
    this._map = map;
    this._dragHandlePosition = destination(point, 90, this._radius/1000);
    this._dragHandle = new GMarker(this._dragHandlePosition, queryLineOptions);
    this._centerHandlePosition = point;
    this._centerHandle = new GMarker(this._centerHandlePosition, queryCenterOptions);
    this._color = this.COLORS[COLORI++ % 3];
    map.addOverlay(this._dragHandle);
    map.addOverlay(this._centerHandle);
    var myObject = this;
    GEvent.addListener (this._dragHandle, "dragend", function() {myObject.updateCircle(1);});
    GEvent.addListener (this._dragHandle, "drag", function() {myObject.updateCircle(1);});
    GEvent.addListener(this._centerHandle, "dragend", function() {myObject.updateCircle(2);});
    GEvent.addListener(this._centerHandle, "drag", function() {myObject.updateCircle(2);});
}

GeoQuery.prototype.updateCircle = function (type) {
	// type = 1 : rayon ; type=2: centre
	
    this._map.removeOverlay(this._polyline);
    if (type==1) {
      this._dragHandlePosition = this._dragHandle.getPoint();
      this._radius = distance(this._centerHandlePosition, this._dragHandlePosition) * 1000;
      this.render();
    } else {
      this._centerHandlePosition = this._centerHandle.getPoint();
      this.render();
      this._dragHandle.setPoint(this.getEast());
    }
}

GeoQuery.prototype.render = function() {
  if (this._type == this.CIRCLE) {
    this._points = [];
    var distance = this._radius/1000;
    for (i = 0; i < 72; i++) {
      this._points.push(destination(this._centerHandlePosition, i * 360/72, distance) );
    }
    this._points.push(destination(this._centerHandlePosition, 0, distance) );
    //this._polyline = new GPolyline(this._points, this._color, 6);
    this._polyline = new GPolygon(this._points, this._color, 1, 1, this._color, 0.2);
	this._map.addOverlay(this._polyline);
    
	this.limites.extend(this._polyline.getBounds().getNorthEast());
	this.limites.extend(this._polyline.getBounds().getSouthWest());
	
	
	this._control.render();
	
	updateForm();
	

	
	
  }
}

GeoQuery.prototype.remove = function() {
  this._map.removeOverlay(this._polyline);
  this._map.removeOverlay(this._dragHandle);
  this._map.removeOverlay(this._centerHandle);
  
}

GeoQuery.prototype.getRadius = function() {
    return this._radius;
}

GeoQuery.prototype.getHTML = function() {
  return "<span><font color='"+ this._color + "''>" + this.getDistHtml() + "</font></span>";
}

GeoQuery.prototype.getDistHtml = function() {
  result = "<img src='http://www.acqsion.com/img/close.gif' onClick='myQueryControl.remove(" + this._control.getIndex(this) + ");'/>Rayon :";
  if (metric) {
    if (this._radius < 1000) {
      result += this._radius.toFixed(0) +' m';
    } else {
      result += (this._radius / 1000).toFixed(1)+ ' km';
    }
  } else {
    var radius = this._radius * 3.2808399;
    if (radius < 5280) {
      result += "in feet : " + radius.toFixed(1);
    } else {
      result += "in miles : " + (radius / 5280).toFixed(1);
    }
  }
  return result;   
}

GeoQuery.prototype.getNorth = function() {
  return this._points[0];
}

GeoQuery.prototype.getSouth = function() {
  return this._points[(72/2)];
}

GeoQuery.prototype.getEast = function() {
  return this._points[(72/4)];
}

GeoQuery.prototype.getWest = function() {
  return this._points[(72/4*3)];
}



function QueryControl (localSearch) {
  this._localSearch = localSearch;
}



QueryControl.prototype = new GControl();
QueryControl.prototype._geoQueries ;
QueryControl.prototype._mainDiv;
QueryControl.prototype._queriesDiv;
QueryControl.prototype._minStar;
QueryControl.prototype._minPrice;
QueryControl.prototype._maxPrice;
QueryControl.prototype._timeout;
QueryControl.prototype._localSearch;

QueryControl.prototype.initialize = function(map) {
  this._mainDiv = document.createElement("div");
  this._mainDiv.id = "GQueryControl";
  titleDiv = document.createElement("div");
  titleDiv.id = "GQueryControlTitle";
  titleDiv.appendChild(document.createTextNode("Vos zones de recherche"));
  this._mainDiv.appendChild(titleDiv);
  this._queriesDiv = document.createElement("div");
  this._queriesDiv.id = "queriesDiv";
  this._mainDiv.appendChild(this._queriesDiv);

  map.getContainer().appendChild(this._mainDiv);
  this._geoQueries = new Array();
  return this._mainDiv;
}

QueryControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 10));
}

QueryControl.prototype.addGeoQuery = function(geoQuery) {
	
  this._geoQueries.push(geoQuery);
  geoQuery._control = this;
  newDiv = document.createElement("div");
  newDiv.innerHTML = geoQuery.getHTML();
  this._queriesDiv.appendChild(newDiv);
 
}

QueryControl.prototype.render = function() {
  for (i = 0; i < this._geoQueries.length; i++) {
    geoQuery = this._geoQueries[i];
    this._queriesDiv.childNodes[i].innerHTML = geoQuery.getHTML();
  }



}

QueryControl.prototype.query = function() {

}

QueryControl.prototype.remove = function(index) {
  this._geoQueries[index].remove();
  this._queriesDiv.removeChild(this._queriesDiv.childNodes[index]);
  delete this._geoQueries[index];
  this._geoQueries.splice(index,1);
  this.render();
  updateForm();
}


QueryControl.prototype.getNbCircle = function(){
	return (this._geoQueries.length);
}


QueryControl.prototype.getIndex = function(geoQuery) {
  for (i = 0; i < this._geoQueries.length; i++) {
    if (geoQuery == this._geoQueries[i]) {
      return i;
    }
  }
  return -1;
}


/********************************************************************************
Utilisation pour afficher uniquement les cercles sans possibilité de les modifier
(annonce-achat-immobilier.php)
*/

function startStaticMap(){new StaticMap();};


function StaticMap(){
	
		myMap = new GMap2(document.getElementById("map"));
	
		 //Centrage de la carte
		myMap.setCenter(new GLatLng(37.4419, -122.1419), 13);
		myMap.addControl(new GLargeMapControl3D());
		myMap.addControl(new GMapTypeControl());

		myCercles = new StaticCercle();
		
		
		// Affichage des cercles
		for (var i=0; i<arrayCercles.length; i++){
			myCercles.addCircle(arrayCercles[i]);
		}
	};



function StaticCercle(){
	this.limites = new GLatLngBounds();
}
	
	
StaticCercle.prototype.COLORS=["#0000ff", "#00ff00", "#ff0000"];
StaticCercle.prototype._cercles = [];
StaticCercle.prototype.centre;
StaticCercle.prototype.couleur;


StaticCercle.prototype.addCircle = function(cercle){
	this.centre = new GPoint(cercle.lon,cercle.lat);	
	this.rayon = cercle.rayon/1000;
	this._color = this.COLORS[this._cercles.length % 3];;
    this._points = [];
 
	// ajoute les points sur le cercle
    for (var i = 0; i < 72; i++) {
      this._points.push(destination(this.centre, i * 360/72, this.rayon) );
	  ; 
    }
    this._points.push(destination(this.centre, 0,this.rayon) );
	
	// création de la polyligne
    this._polyline = new GPolygon(this._points, this._color, 1, 1, this._color, 0.2);
	//Affichage du cercle
	myMap.addOverlay(this._polyline);
	
	this.limites.extend(this._polyline.getBounds().getNorthEast());
	this.limites.extend(this._polyline.getBounds().getSouthWest());
	this._cercles.push(cercle);
	
	//centre la carte sur les limites
	var clat = (this.limites.getNorthEast().lat() + this.limites.getSouthWest().lat()) /2;
	var clng = (this.limites.getNorthEast().lng() + this.limites.getSouthWest().lng()) /2;
	
	myMap.panTo(new GLatLng(clat,clng));
	myMap.setZoom(myMap.getBoundsZoomLevel(this.limites)-1);
	return true;
	
	
}

/********************************************************************************
Utilisation pour afficher uniquement un point sur carte
*/

function initialize() {
    var myMap = new google.maps.Map2(document.getElementById("map"));
	myMap.addControl(new GLargeMapControl3D());
  myMap.addControl(new GMapTypeControl());
	
     myMap.setCenter(new GLatLng(43.5,5.526123), 8);

	  var myGeographicCoordinates = new GLatLng(myLatitude, myLongitude); 
      myMap.addOverlay(new GMarker(myGeographicCoordinates));
    }
  





