

//Gmap
var map = null;
//Geocoding
var geocoder = null;
//Calcul d'itinéraire
var gdir;

//zoom courant
var zoom;
//stockage des points
var points = new Array();
var marker=[];
//adresse recherchée. Si null, aucune adresse n'a été recherchée
var adressesearched = null; 
var adressedest = null;
//icone générique
var hotIcon = new GIcon(G_DEFAULT_ICON);
//gabarit pour l'affichage de l'itinéraire
var gabaritItineraire;
//label de l'affichage de l'adresse
var adresseLabel = null;
var handler;
var countctrl = 0;

var depart = null;
var arrivee = null;
var trace = null;

//paramètres de configuration
var radius;
var proxkm;
var proxnb;
var in_adresse_proxcalc;
var in_adresse_winrech;
var in_prox_onover;
var tt_prox_pointonover;
var in_prox_pointonover_x;
var in_prox_pointonover_y;
var tt_depart;
var in_depart_x;
var in_depart_y;
var tt_arrivee;
var in_arrivee_x;
var in_arrivee_y;
var tt_adrimg;
var in_adrimg_x;
var in_adrimg_y;
var in_itionclic;
var tt_urlredirect;




///////////////////////////////////////////////////////////////////////////////////////////////
//GESTION DES POINTS



/* création d'un marqueur sur la carte
	@param index (Number) index du point
	@param urlpoint (String) image affichée
	@param urlpoint_shadow (String) image de l'ombre affichée
*/
/*function createMarker(index, urlpoint, urlpoint_shadow) {
	
	var point = points[index].point;
	
	if (urlpoint != ""){
		var icon = new GIcon();
		icon.image = urlpoint;
		icon.shadow = urlpoint_shadow;

		if (liconSize != undefined) { icon.iconSize = liconSize; }
		if (lshadowSize != undefined) { icon.shadowSize = lshadowSize; }
		if (liconAnchor != undefined) { icon.iconAnchor = liconAnchor; }
		if (linfoWindowAnchor != undefined) { icon.infoWindowAnchor = linfoWindowAnchor; }
			
		var marker = new GMarker(point,icon);
	}else{
		var marker = new GMarker(point);
	}
	
	var fiche = 'fiche'+index;
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(document.getElementById(fiche).innerHTML);
		//marker.openInfoWindowHtml(texte);
		//createTestMarker(index,urlpoint,added.urlpoint_shadow);
	});
	return marker;
}*/


function createMarker2(index, urlpoint, urlpoint_shadow) {
	
	var point = points[index].point;
	
	if (urlpoint != ""){
		var icon = new GIcon();
		icon.image = urlpoint;
		icon.shadow = urlpoint_shadow;
		/*icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);*/
		//console.log(liconSize == undefined);
		//console.log(lshadowSize == undefined);
		if (liconSize != null) { icon.iconSize = liconSize; }
		if (lshadowSize != null) { icon.shadowSize = lshadowSize; }
		if (liconAnchor != null) { icon.iconAnchor = liconAnchor; }
		if (linfoWindowAnchor != null) { icon.infoWindowAnchor = linfoWindowAnchor; }
			
		var marker = new GMarker(point,icon);
	}else{
		var marker = new GMarker(point);
	}
	
	var fiche = 'fiche'+index;
	
	GEvent.addListener(marker, "mouseover", function() {
		//marker.openInfoWindowHtml(document.getElementById(fiche).innerHTML);
		//marker.openInfoWindowHtml(texte);
		createTestMarker(index);
	});
	
	if (in_itionclic == 1 && tt_urlredirect == ""){
	GEvent.addListener(marker, "click", function() {
		go(index);
	});
	}
	
	if (tt_urlredirect != "" && points[index].hasurl == 1){
	GEvent.addListener(marker, "click", function() {
		document.location=tt_urlredirect+"="+points[index].pk;
	});
	}
	
	
	GEvent.addListener(marker, "mouseout", function() {
		//marker.openInfoWindowHtml(document.getElementById(fiche).innerHTML);
		//marker.openInfoWindowHtml(texte);
		//createTestMarker(index,urlpoint,urlpoint_shadow);
		
		
		map.removeTLabel(points[index].tlabel);
	});
	return marker;
}


				
				


function createTestMarker(index){
	var fiche = 'fiche'+index;
	var content = document.getElementById(fiche).innerHTML;
	
	var point = points[index].point;
	
	var label = new TLabel();
	label.id = 'fiche';
	label.anchorLatLng = new GLatLng (point.lat(),point.lng());
	label.anchorPoint = 'bottomLeft';
	if (labelanchor != null) {
		label.markerOffset = labelanchor;
	}
	else {
		label.markerOffset = new GSize (0,0);
	}
	label.content = content;
	label.percentOpacity = 100;
	
	points[index].tlabel = label;
	
	map.addTLabel(label);
}


function openAdresseWindow(localisation,content){
	document.getElementById("adressefiche_content").innerHTML = content;
	var content = document.getElementById("adressefiche").innerHTML;
	
	//content = "test";
	
	var label = new TLabel();
	label.id = 'adresseinfo';
	label.anchorLatLng = localisation;
	label.anchorPoint = 'bottomLeft';
	label.markerOffset = new GSize (-20,0);
	label.content = content;
	label.percentOpacity = 100;
	
	adresseLabel = label;
	
	map.addTLabel(label);
}

function closeAdresseWindow(){
	map.removeTLabel(adresseLabel);
	adresseLabel = null;
}


function closeAdresseWindowIfOpened(){
	if (adresseLabel != null){
		closeAdresseWindow();
	}
}



/* mise en avant d'un point
	@param num (Number) index du point
*/
function heat(num){
	
	
	if (tt_prox_pointonover != "" && tt_prox_pointonover != "/"){
		var icon = new GIcon();
		icon.image = tt_prox_pointonover;
		icon.iconAnchor = new GPoint(in_prox_pointonover_x, in_prox_pointonover_y);
		
		attract = new GMarker(points[num].point,icon);
	}else{
		attract = new GMarker(points[num].point,hotIcon);	
	}
	
	
	
	
	map.addOverlay(attract);
}


/* masquage d'un point
	@param num (Number) index du point
*/
function cool(num){
	map.removeOverlay(attract);
}



///////////////////////////////////////////////////////////////////////////////////////////////
//CALCUL D'ITINERAIRES


/* calcul d'un itinéraire vers un point
	si pas d'adrsse de départ spécifiée par une recherche : point de départ = coordonnées courantes
	si adresse de départ spécifiée : point de départ = adresse
	@param num (Number) index du point
*/
function go(num){
	
	closeAdresseWindowIfOpened();
	
	var current = map.getCenter();
	var point = points[num].point;
	
	adressedest = points[num].adresse;
	
	if (adressesearched == null || adressesearched == "localisation courante"){
		adressesearched = "localisation courante";
		setDirections(current.toUrlValue(), point.toUrlValue(), "fr");
	}else{
		setDirections(adressesearched, point.toUrlValue(), "fr");
	}
	
}


/*	tracage d'un itinéraire
	@param fromAdress (String) adresse ou coordonnées de départ
	@param toAdress (String) adresse ou coordonnées d''arrivée
	@param locale (String) code langue (fr par exemple)
*/
function setDirections(fromAddress, toAddress, locale) {
	
	gdir.getSteps = false;
	countctrl = 0;
	handler = GEvent.addListener(map,"addoverlay", verifyAfterIti);
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
	  
	  //clearIti();
}


function verifyAfterIti(objet){
	countctrl++;
	if (countctrl == 2){
		placeFirstPoint(objet);
	}
	if (countctrl == 4){
		placeSecondPoint(objet);
		GEvent.removeListener(handler);
	}
	
}

function placeFirstPoint(objet){
	
	if (depart != null){
		map.removeOverlay(depart);	
	}
	
	objet.hide();
	var point = objet.getPoint();
	
	var icon = new GIcon();
	icon.image = tt_depart;
	icon.iconAnchor = new GPoint(in_depart_x, in_depart_y);
	
	if (tt_depart != '' && tt_depart != '/'){
		depart = new GMarker(point,icon);
	}else{
		depart = new GMarker(point);
	}
	
	map.addOverlay(depart);
}


function placeSecondPoint(objet){
	
	if (arrivee != null){
		map.removeOverlay(arrivee);	
	}
	
	objet.hide();
	var point = objet.getPoint();
	
	var icon = new GIcon();
	icon.image = tt_arrivee;
	icon.iconAnchor = new GPoint(in_arrivee_x, in_arrivee_y);
	
	if (tt_arrivee != '' && tt_arrivee != '/'){
		arrivee = new GMarker(point,icon);
	}else{
		arrivee = new GMarker(point);
	}
	map.addOverlay(arrivee);
}


function onGDirectionsLoad(){
	generateIti();
}

function generateIti(){
	
	var dest = document.getElementById('drivingInfo');
	var gabarit = gabaritItineraire;
	
	var route = gdir.getRoute(0);
	var nombre = route.getNumSteps();
	
	//remplacement des zones non duplicables
	gabarit = gabarit.replace("!depart/!",adressesearched);
	gabarit = gabarit.replace("!totalresume/!",route.getSummaryHtml());
	gabarit = gabarit.replace("!arrivee/!",adressedest);
	
	//recherche du gabarit de la ligne
	var expr = new RegExp("\!openlist/\!.*?!closelist/\!","gi");
	//alert(expr.test(gabarit));
	var gabline = expr.exec(gabarit).toString();
	gabline = gabline.replace("!openlist/!","");
	gabline = gabline.replace("!closelist/!","");
	
	
	//construction des lignes
	var content = "";
	for(var i=0; i<nombre; i++){
		var step = route.getStep(i);
		var line = gabline;
		line = line.replace("!resume/!",step.getDescriptionHtml());
		line = line.replace("!distance/!",step.getDistance().html);
		line = line.replace("!duree/!",step.getDuration().html);
		content += line;
	}
	
	
	var regexp = new RegExp("\!openlist/\!.*?!closelist/\!","gi");
	gabarit = gabarit.replace(regexp,content);
	
	
	dest.innerHTML = gabarit;
	
}







///////////////////////////////////////////////////////////////////////////////////////////////
//GEOCODAGE D'UNE ADRESSE


/*	recherche d'une adresse
	@param adress (String) adresse à rechercher
*/
function goToAdresse(address) {
	
	setSearchError(false);
	closeAdresseWindowIfOpened();
	
	if (depart != null){
		map.removeOverlay(depart);	
	}
	
	if (arrivee != null){
		map.removeOverlay(arrivee);	
	}
	
	//gdir.clear();
	
	
	
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        setSearchError(true);
      } else {
		  adressesearched = address;
        map.setCenter(point, zoom);
		
		var icon = new GIcon();
		icon.image = tt_adrimg;
		icon.iconAnchor = new GPoint(in_adrimg_x, in_adrimg_y);
		
        if (tt_adrimg != '' && tt_adrimg != '/'){
		var marker = new GMarker(point,icon);
		}else{
		var marker = new GMarker(point);
		}
        map.addOverlay(marker);
        //marker.openInfoWindowHtml(address);
		
		if (in_adresse_winrech == 1){
			openAdresseWindow(point,address);
		}
		//createTestMarker(index, urlpoint, urlpoint_shadow)
		
		if (in_adresse_proxcalc == 1){
			proxCalc();
		}
      }
    }
  );
}


function setSearchError(etat){
	try{
		if (etat){
			document.getElementById('googlemap_searcherror').style.display = "";
		}else{
			document.getElementById('googlemap_searcherror').style.display = "none";
		}
	}catch(err){
	}	
}

///////////////////////////////////////////////////////////////////////////////////////////////
//GESTION DE LA RECHERCHE A PROXIMITE


/*	calcul et affichage des points à proximité
*/
function proxCalc(){
	var distances=[];
	var mainpoint = map.getCenter();
	
	for (var i=0; i<points.length; i++){
		var point = points[i].point;
		var distance = point.distanceFrom(mainpoint);
		distances.push({distance:distance,tt_libelle:points[i].libelle, tt_descriptif:points[i].descriptif, index:i, urlpoint:points[i].urlpoint});
	}
	
	distances=distances.sort(function (a,b) {return (a.distance - b.distance)}); 
	
	
	//récupération du gabarit
	var gabarit = document.getElementById("proximite").innerHTML;
	
	var content = "";
	var content2 = "";
	
	var n = 0;
	
	
	
	
	var divider = 0;
	for (var j=0; j<distances.length && j<proxnb; j++){
		if (distances[j].distance<radius){
			divider++;
		}
	}
	
	var divide = -1;
	if (document.getElementById("distanceInfo2") != null){
		divide = Math.ceil(divider/2);
	}


	for (var j=0; j<distances.length && j<proxnb; j++){
		if (distances[j].distance<radius){
			n++;
			
			var ins = gabarit;
			ins = ins.replace("!image/!", "<img src='"+distances[j].urlpoint+"'>");

			while(ins.indexOf("\!numero\/\!") != -1){
				ins = ins.replace("!numero/!",n);
			};
			
			ins = ins.replace("!nom/!",distances[j].tt_libelle);
			ins = ins.replace("!distance/!",(distances[j].distance/1000).toFixed(1));
			ins = ins.replace("!descriptif/!",distances[j].tt_descriptif);
			
			var expr = new RegExp("\!yaller/\!.*?!yaller/\!","gi");
			var titrelien = expr.exec(ins).toString();
			titrelien = titrelien.replace("!yaller/!","");
			titrelien = titrelien.replace("!yaller/!","");
			
			var regexp = new RegExp("\!yaller/\!.*?!yaller/\!","gi");
			var lien = "<a class='lien' style='cursor:pointer;' onClick='go("+distances[j].index+")' ";
			
			if (in_prox_onover == 1){
				lien += "onmouseover='heat("+distances[j].index+")' onmouseout='cool("+distances[j].index+")'";
			}
			
			lien += ">"+titrelien+"</a>";
			ins = ins.replace(regexp,lien);
			
			
			var expr = new RegExp("\!centrer/\!.*?!centrer/\!","gi");
			var titrelien = expr.exec(ins).toString();
			titrelien = titrelien.replace("!centrer/!","");
			titrelien = titrelien.replace("!centrer/!","");
			
			var regexp = new RegExp("\!centrer/\!.*?!centrer/\!","gi");
			var lien = "<a class='lien' style='cursor:pointer;' onClick='centrer("+distances[j].index+");' ";
			
			if (in_prox_onover == 1){
				lien += "onmouseover='heat("+distances[j].index+")' onmouseout='cool("+distances[j].index+")'";
			}
			
			lien += ">"+titrelien+"</a>";
			ins = ins.replace(regexp,lien);
			
			
			if (divide != -1 && j<divide){
				content += ins;
			}else if(divide != -1){
				content2 += ins;
			}else{
				content += ins;
			}
			
			
			//content +=  "<div id='proxline'><span class='numero'>"+n+"</span> - <span class='nom'>"+distances[j].tt_libelle+"</span> <span class='km'>("+(distances[j].distance/1000).toFixed(1) +" km)</span> <a class='lien' style='cursor:pointer;' onClick='go("+distances[j].index+")' onmouseover='heat("+distances[j].index+")' onmouseout='cool("+distances[j].index+")'>y aller</a></div>";
		}
	}
	
	if (divide != -1){
		document.getElementById("distanceInfo").innerHTML = content;
		document.getElementById("distanceInfo2").innerHTML = content2;
	}else{
		document.getElementById("distanceInfo").innerHTML = content;
	}
	
}



function centrer(num){
	var point = points[num].point;
	
	map.setCenter(point,zoom);
	closeAdresseWindowIfOpened();
	proxCalc();
}


///////////////////////////////////////////////////////////////////////////////////////////////
//GESTION DES CONTROLES ZOOM SPECIFIQUES

var p_plus_img;
var p_plus_vd;
var p_plus_hd;
var p_moins_img;
var p_moins_vd;
var p_moins_hd;


function TextualZoomControl(plus_img,plus_vd,plus_hd,moins_img,moins_vd,moins_hd) {
	p_plus_img = plus_img;
	p_plus_vd = plus_vd;
	p_plus_hd = plus_hd;
	p_moins_img = moins_img;
	p_moins_vd = moins_vd;
	p_moins_hd = moins_hd;
}
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  zoomInDiv.style.position = "absolute";
  zoomInDiv.style.left = p_plus_hd+"px";
  zoomInDiv.style.top = p_plus_vd+"px";
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  var image = document.createElement("img");
  image.src = p_plus_img;
  image.id = "zoominplus";
  zoomInDiv.appendChild(image);
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
	zoom = map.getZoom();
  });

  var zoomOutDiv = document.createElement("div");
  zoomOutDiv.style.position = "absolute";
  zoomOutDiv.style.left = p_moins_hd+"px";
  zoomOutDiv.style.top = p_moins_vd+"px";
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  var image = document.createElement("img");
  image.src = p_moins_img;
  zoomOutDiv.appendChild(image);
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
	zoom = map.getZoom();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textAlign = "center";
  button.style.cursor = "pointer";
}



///////////////////////////////////////////////////////////////////////////////////////////////
//GESTION DES CONTROLES PAN SPECIFIQUES


var p_top_img;
var p_top_vd;
var p_top_hd;
var p_right_img;
var p_right_vd;
var p_right_hd;
var p_left_img;
var p_left_vd;
var p_left_hd;
var p_bottom_img;
var p_bottom_vd;
var p_bottom_hd;

function TextualDeplacementControl(top_img,top_vd,top_hd,right_img,right_vd,right_hd,left_img,left_vd,left_hd,bottom_img,bottom_vd,bottom_hd) {
	p_top_img = top_img;
	p_top_vd = top_vd;
	p_top_hd = top_hd;
	p_right_img = right_img;
	p_right_vd = right_vd;
	p_right_hd = right_hd;
	p_left_img = left_img;
	p_left_vd = left_vd;
	p_left_hd = left_hd;
	p_bottom_img = bottom_img;
	p_bottom_vd = bottom_vd;
	p_bottom_hd = bottom_hd;
}
TextualDeplacementControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualDeplacementControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var top = document.createElement("div");
  top.style.position = "absolute";
  top.style.left = p_top_hd+"px";
  top.style.top = p_top_vd+"px";
  this.setButtonStyle_(top);
  container.appendChild(top);
  var image = document.createElement("img");
  image.src = p_top_img;
  top.appendChild(image);
  GEvent.addDomListener(top, "click", function() {
	map.panDirection(0,+1);
  });
  
  var right = document.createElement("div");
  right.style.position = "absolute";
  right.style.left = p_right_hd+"px";
  right.style.top = p_right_vd+"px";
  this.setButtonStyle_(right);
  container.appendChild(right);
  var image = document.createElement("img");
  image.src = p_right_img;
  right.appendChild(image);
  GEvent.addDomListener(right, "click", function() {
	map.panDirection(-1,0);
  });
  
  var left = document.createElement("div");
  left.style.position = "absolute";
  left.style.left = p_left_hd+"px";
  left.style.top = p_left_vd+"px";
  this.setButtonStyle_(left);
  container.appendChild(left);
  var image = document.createElement("img");
  image.src = p_left_img;
  left.appendChild(image);
  GEvent.addDomListener(left, "click", function() {
	map.panDirection(+1,0);
  });
  
  var bottom = document.createElement("div");
  bottom.style.position = "absolute";
  bottom.style.left = p_bottom_hd+"px";
  bottom.style.top = p_bottom_vd+"px";
  this.setButtonStyle_(bottom);
  container.appendChild(bottom);
  var image = document.createElement("img");
  image.src = p_bottom_img;
  bottom.appendChild(image);
  GEvent.addDomListener(bottom, "click", function() {
	map.panDirection(0,-1);
  });



  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualDeplacementControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualDeplacementControl.prototype.setButtonStyle_ = function(button) {
  button.style.textAlign = "center";
  button.style.cursor = "pointer";
}


