var racine = racine ? racine : '/';
var urlPictosMarkers = racine+"img/maps/";

var urlGmap = "/fr/plan_interactif_business";

var mapProximite = null;
function setMapProxi(map){
    mapProximite = map;
}
function getMapProxi(){
    return mapProximite;
}

var tabCorrespondTypes = [];
tabCorrespondTypes["225"] = 1; /* HOTELS */
tabCorrespondTypes["226"] = 2; /* CONGRES */
tabCorrespondTypes["227"] = 3; /* RESTAURANTS */
tabCorrespondTypes["228"] = 4; /* PARCS */

var trafficOptions = {incidents:true};
var trafficInfo = new GTrafficOverlay(trafficOptions);

function initialize(jsonFlux) {
}

function initializeNormal(jsonFlux) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("gmap"));
		map.setCenter(new GLatLng(48.868719,2.7818), 15);
		var zoomControl = new TextualZoomControl(map);
		map.addControl(zoomControl);
		map.enableScrollWheelZoom();
		map.setMapType(G_HYBRID_MAP);
		
		// lancement du placement des points sur la map
		addPointsByJson(jsonFlux,map)
		return map;
	}
}
function initializeLittleMap(jsonFlux) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("gmap"));
		map.setCenter(new GLatLng(48.868719,2.7818), 15);
		if(document.getElementById("gmapControlers")){
			var zoomControl = new TextualZoomControl(map);
		}else{
			var zoomControl = "no zoom"
		}
		if(zoomControl != "no zoom"){
			map.addControl(zoomControl);
		}else{
			map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10)));
			map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10)));
		}
		map.enableScrollWheelZoom();
		map.setMapType(G_HYBRID_MAP);		
		
		// lancement du placement des points sur la map
		addLittlePointsByJson(jsonFlux,map)
		
		return map;
	}
}
var GmapJSON;
function addLittlePointsByJson(jsonFlux,map){

	GmapJSON = jsonFlux;

	// on verifie que le flux JSON est au bon format
	if(jsonFlux.googlemaps){
		var nbrOffres = jsonFlux.googlemaps.offre?jsonFlux.googlemaps.offre.length:0;
		if(nbrOffres != 0){
			var mesOffres = jsonFlux.googlemaps.offre;
			setMapProxi(map); 
			for(var i=0;i<nbrOffres;i++){
				
				if(mesOffres[i].type=="XX"){
					//console.log("transport lite");
					/*
						Bloc LITE ELEMENT TRANSPORT
					*/
					var obj = mesOffres[i];
					
					// Fabrication de l icone
					var letter = "";
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					var letteredIcon = new GIcon(baseIcon);
					letteredIcon.image = urlPictosMarkers+"accesicon.png";
					letteredIcon.printImage = urlPictosMarkers+"accesicon.png";
					letteredIcon.iconSize =  new GSize(37, 39);
					letteredIcon.iconAnchor = new GPoint(37, 39);
					letteredIcon.infoWindowAnchor = new GPoint(37, 39);
					letteredIcon.imageMap = [0,0, 38,0, 38,30, 0,30, 0,0];
					
					// fabrication du HTML
					var contentWindowHTMLLite = "";
					contentWindowHTMLLite += '<div class="myWindowGmapLite BpaddingLg">';
					contentWindowHTMLLite += '<div class="text">';
					contentWindowHTMLLite += '<h2>'+obj.nom1+'</h2>';
					contentWindowHTMLLite += '<p class="adress">'+obj.accroche+'</p>';
					/**/
					if(obj.push.length != 0){
						contentWindowHTMLLite += '<div class="specialLinks"><h3>'+f6_googlemaps_addLittlePointsByJson_liens_pratiques+'</h3>';
						contentWindowHTMLLite += '<ul>';
						for(var j=0; j<obj.push.length;j++){
							contentWindowHTMLLite += '<li><a href="'+obj.push[j].link+'" target="_blank">'+obj.push[j].value+'</a></li>';
						}
						contentWindowHTMLLite += '</ul>';
						contentWindowHTMLLite += '</div>';
					}
					/**/
					contentWindowHTMLLite += '<div class="specialLinks2">';
					contentWindowHTMLLite += '<p class="bigMap"><a href="'+urlGmap+'" target="_blank">'+f6_googlemaps_addLittlePointsByJson_voir_toutes_offres+' '+f6_dfomain_gmap_categories_hotel+'</a></p>';		
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '<div class="bottomWindowGmap">&nbsp;</div>';
					
					
					var point = new GLatLng(obj.longitude,obj.latitude);
					//map.addOverlay(createMarkerTransportLite(idMap, map, point, i, mesOffres[i]));
					map.addOverlay(createMarkerElement(point, contentWindowHTMLLite, letteredIcon, map, false));
					
				}else{
					//console.log("normal lite");
					/*
						Bloc LITE ELEMENT
					*/
					var obj = mesOffres[i];
					
					// Fabrication de l icone
					var letter = ""+obj.identifier;
					letter = letter.toUpperCase();
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					var letteredIcon = new GIcon(baseIcon);
					letteredIcon.image = urlPictosMarkers+tabCorrespondTypes[""+obj.type]+"/"+"marker_" + letter + ".png";
					letteredIcon.printImage = urlPictosMarkers+tabCorrespondTypes[""+obj.type]+"/"+"marker_" + letter + ".png";
					letteredIcon.shadowSize  = new GSize(1, 1);
					letteredIcon.iconSize =  new GSize(52, 42);
					letteredIcon.iconAnchor = new GPoint(0, 42);
					letteredIcon.infoWindowAnchor = new GPoint(100,60);
					letteredIcon.imageMap = [43,0,44,1,45,2,46,3,47,4,47,5,47,6,48,7,49,8,50,9,51,10,51,11,51,12,51,13,51,14,51,15,51,16,51,17,51,18,51,19,51,20,51,21,51,22,51,23,51,24,51,25,51,26,51,27,51,28,51,29,51,30,51,31,51,32,51,33,51,34,50,35,50,36,49,37,47,38,45,39,49,40,10,41,4,41,4,40,4,39,0,38,0,37,0,36,0,35,0,34,0,33,0,32,0,31,0,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,1,3,1,2,2,1,4,0];
					
					// fabrication du HTML
					var adresse = ""+encodeURIComponent(obj.adresse.value);
					adresse += "+"+encodeURIComponent(obj.adresse.cp);
					adresse += "+"+encodeURIComponent(obj.adresse.ville);
				
					var contentWindowHTMLLite = "";
					contentWindowHTMLLite += '<div class="myWindowGmapLite">';
					contentWindowHTMLLite += '<div class="text">';
					contentWindowHTMLLite += '<h2>'+obj.nom2+'</h2>';
					contentWindowHTMLLite += '<p class="voirFiche">&gt; <a href="'+obj.urlmore+'">'+f6_googlemaps_addLittlePointsByJson_voir_fiche+'</a></p>';
					contentWindowHTMLLite += '<div class="specialLinks2"><h3>'+f6_googlemaps_addLittlePointsByJson_liens_pratiques+'</h3>';
					if(obj.latitude != "") {
						contentWindowHTMLLite += '<p class="showItineraire"><a href="http://maps.google.fr/maps?daddr='+obj.longitude+','+obj.latitude+'" class="gothere" target="_blank"><span>'+f6_googlemaps_addLittlePointsByJson_go_to+'</span></a></p>';
					}
					if (obj.adresse.ville != "") {
						contentWindowHTMLLite += '<p class="showItineraire"><a href="http://maps.google.fr/maps?saddr='+adresse+'" class="getFrom" target="_blank"><span>'+f6_googlemaps_addLittlePointsByJson_go_back+'</span></a></p>';
					}
					if(obj.latitude != "") {
						contentWindowHTMLLite += '<p class="showItineraire"><a href="#" onclick="proximiteMap('+obj.longitude+','+obj.latitude+', GmapJSON);return false;" class="getProximite" ><span>'+f6_googlemaps_addLittlePointsByJson_close_to+'</span></a></p>';
					}
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '<div class="specialLinks2">';
					contentWindowHTMLLite += '<p class="bigMap"><a href="'+urlGmap+'" target="_blank">'+f6_googlemaps_addLittlePointsByJson_voir_toutes_offres+'</a></p>';		
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '</div>';
					contentWindowHTMLLite += '<div class="bottomWindowGmap">&nbsp;</div>';
					
					var point = new GLatLng(obj.longitude,obj.latitude);
					//map.addOverlay(createLiteMark(idMap, map, point, i, mesOffres[i]));
					map.addOverlay(createMarkerElement(point, contentWindowHTMLLite, letteredIcon, map, false));
				}
			}
		}
	}
}

function addPointsByJson(jsonFlux,map){
	
	// on verifie que le flux JSON est au bon format
	if(jsonFlux.googlemaps){
		var nbrOffres = jsonFlux.googlemaps.offre?jsonFlux.googlemaps.offre.length:0;
		if(nbrOffres != 0){
			var mesOffres = jsonFlux.googlemaps.offre;
			
			for(var i=0;i<nbrOffres;i++){
				
				if(mesOffres[i].type=="XX"){
					//console.log("transport");
					/*
						Bloc ELEMENT TRANSPORT
					*/
					var obj = mesOffres[i];
					
					// Fabrication de l icone
					var letter = "";
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					var letteredIcon = new GIcon(baseIcon);
					letteredIcon.image = urlPictosMarkers+"accesicon.png";
					letteredIcon.printImage = urlPictosMarkers+"accesicon.png";
					letteredIcon.iconSize =  new GSize(37, 39);
					letteredIcon.iconAnchor = new GPoint(37, 39);
					letteredIcon.infoWindowAnchor = new GPoint(37, 39);
					letteredIcon.imageMap = [0,0, 38,0, 38,30, 0,30, 0,0];
					
					// fabrication du HTML
					var contentWindowHTML1 = "";
					contentWindowHTML1 += '<div class="myWindowGmap">';
					contentWindowHTML1 += '<div class="mea meaRight">';
					if(obj.img != ""){
						contentWindowHTML1 += '<div class="media">&nbsp;<img src="'+obj.img+'" alt="" /></div>';
					}
					contentWindowHTML1 += '<div class="text">';
					contentWindowHTML1 += '<h2>'+obj.nom1+'</h2>';
					contentWindowHTML1 += '<p class="adress">'+obj.accroche+'</p>';
					contentWindowHTML1 += '</div>';
					contentWindowHTML1 += '</div>';
					/**/
					if(obj.push.length != 0){
						contentWindowHTML1 += '<div class="specialLinks"><h3>'+f6_googlemaps_addPointsByJson_infos_cles+':</h3>';
						contentWindowHTML1 += '<ul>';
						for(var j=0; j<obj.push.length;j++){
							contentWindowHTML1 += '<li><a href="'+obj.push[j].link+'" target="_blank">&bull; '+obj.push[j].value+'</a></li>';
						}
						contentWindowHTML1 += '</ul>';
						contentWindowHTML1 += '</div>';
					}
					/**/
					contentWindowHTML1 += '</div>';
					contentWindowHTML1 += '<div class="bottomWindowGmap">&nbsp;</div>';
					
					
					var point = new GLatLng(obj.longitude,obj.latitude);
					//map.addOverlay(createMarkerTransportLite(idMap, map, point, i, mesOffres[i]));
					map.addOverlay(createMarkerElement(point, contentWindowHTML1, letteredIcon, map, true));
					
				}else{
					//console.log("normal");
					/*
						Bloc ELEMENT
					*/
					
					var obj = mesOffres[i];
					
					// Fabrication de l icone
					var letter = ""+obj.identifier;
					letter = letter.toUpperCase();
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					var letteredIcon = new GIcon(baseIcon);
					letteredIcon.image = urlPictosMarkers+tabCorrespondTypes[""+obj.type]+"/"+"marker_" + letter + ".png";
					letteredIcon.printImage = urlPictosMarkers+tabCorrespondTypes[""+obj.type]+"/"+"marker_" + letter + ".png";
					letteredIcon.shadowSize  = new GSize(1, 1);
					letteredIcon.iconSize =  new GSize(52, 42);
					letteredIcon.iconAnchor = new GPoint(0, 42);
					letteredIcon.infoWindowAnchor = new GPoint(120,60);
					letteredIcon.imageMap = [43,0,44,1,45,2,46,3,47,4,47,5,47,6,48,7,49,8,50,9,51,10,51,11,51,12,51,13,51,14,51,15,51,16,51,17,51,18,51,19,51,20,51,21,51,22,51,23,51,24,51,25,51,26,51,27,51,28,51,29,51,30,51,31,51,32,51,33,51,34,50,35,50,36,49,37,47,38,45,39,49,40,10,41,4,41,4,40,4,39,0,38,0,37,0,36,0,35,0,34,0,33,0,32,0,31,0,30,0,29,0,28,0,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,1,3,1,2,2,1,4,0];
					
					// fabrication du HTML
					var adresse = ""+encodeURIComponent(obj.adresse.value);
					adresse += "+"+encodeURIComponent(obj.adresse.cp);
					adresse += "+"+encodeURIComponent(obj.adresse.ville);
				
					var adresse = ""+encodeURIComponent(obj.adresse.value);
					adresse += "+"+encodeURIComponent(obj.adresse.cp);
					adresse += "+"+encodeURIComponent(obj.adresse.ville);
				
					var contentWindowHTML2 = "";
					contentWindowHTML2 += '<div class="myWindowGmap">';
					contentWindowHTML2 += '<div class="mea meaRight">';
					if(obj.img != ""){
						contentWindowHTML2 += '<div class="media">&nbsp;<img src="'+obj.img+'" alt="" /></div>';
					}
					contentWindowHTML2 += '<div class="text">';
					contentWindowHTML2 += '<h2>'+obj.nom2+'</h2>';
					if (obj.adresse.ville != ""){
						contentWindowHTML2 += '<p class="adress">'+obj.adresse.value+'<br />'+obj.adresse.cp+' '+obj.adresse.ville+'</p>';
					}
					if (obj.latitude != ""){
						contentWindowHTML2 += '<p class="showItineraire"><a href="http://maps.google.fr/maps?daddr='+obj.longitude+','+obj.latitude+'" class="gothere" target="_blank"><span>'+f6_googlemaps_addLittlePointsByJson_go_to+'</span></a></p>';
					}
					if (obj.urlmore != ""){
						contentWindowHTML2 += '<p class="showItineraire"><a href="'+obj.urlmore+'" class="gothere"><span>'+f6_dfomain_gmap_en_savoir_plus+'</span></a></p>';
					}
					contentWindowHTML2 += '</div>';
					contentWindowHTML2 += '</div>';
					
					/**/
					if(obj.push.length != 0){
						contentWindowHTML2 += '<div class="specialLinks"><h3>'+f6_googlemaps_addPointsByJson_infos_cles+':</h3>';
						contentWindowHTML2 += '<ul>';
						for(var j=0; j<obj.push.length;j++){
							//console.log(obj.push[j])
							if(obj.push[j].link){
								contentWindowHTML2 += '<li><a href="'+obj.push[j].link+'" target="_blank">&bull; '+obj.push[j].value+'</a></li>';
							}
						}
						contentWindowHTML2 += '</ul>';
						contentWindowHTML2 += '</div>';
					}
					/**/
					contentWindowHTML2 += '</div>';
					contentWindowHTML2 += '<div class="bottomWindowGmap">&nbsp;</div>';
					
					var point = new GLatLng(obj.longitude,obj.latitude);
					//map.addOverlay(createLiteMark(idMap, map, point, i, mesOffres[i]));
					map.addOverlay(createMarkerElement(point, contentWindowHTML2, letteredIcon, map, true));
				}
			}
		}
	}
}


// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).

// We define the function first
function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
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) {
	// div contenant les zones de boutons (sera repositionnee en absolute avec les positions definies dans la fonction TextualZoomControl.prototype.getDefaultPosition
	if(document.getElementById("gmapControlers")){
		var container = document.getElementById("gmapControlers");
		// btn de zoom In
		if(document.getElementById("btnZoomPlus")){
			var zoomInDiv = document.getElementById("btnZoomPlus");
			GEvent.addDomListener(zoomInDiv, "click", function() {
				map.zoomIn();
			});
		}
		// btn de zoom Out
		if(document.getElementById("btnZoomMoins")){
			var zoomOutDiv = document.getElementById("btnZoomMoins");
			GEvent.addDomListener(zoomOutDiv, "click", function() {
				map.zoomOut();
			});
		}
		// btn de changement de map en Mixed Satellite et Plan
		if(document.getElementById("btnSatellite")){
			var satelliteDiv = document.getElementById("btnSatellite");
			GEvent.addDomListener(satelliteDiv, "click", function() {
				trafficInfo.hide();
				map.setMapType(G_HYBRID_MAP);
			});
		}
		// btn de changement de map en Plan
		if(document.getElementById("btnPlan")){
			var planDiv = document.getElementById("btnPlan");
			GEvent.addDomListener(planDiv, "click", function() {
				trafficInfo.hide();
				map.setMapType(G_NORMAL_MAP);
			});
		}
		//if(document.getElementById("btnTrafic")){
		//	var traficDiv = document.getElementById("btnTrafic");
		//	GEvent.addDomListener(traficDiv, "click", function() {
		//		map.setMapType(G_NORMAL_MAP);
		//		trafficInfo.show();
		//		map.addOverlay(trafficInfo);
		//	});
		//}
		if(document.getElementById("btnRelief")){
			var reliefDiv = document.getElementById("btnRelief");
			GEvent.addDomListener(reliefDiv, "click", function() {
				trafficInfo.hide();
				map.setMapType(G_PHYSICAL_MAP);
			});
		}
		// On renvoie le conteneur complet pour la gestion des actions sur la map
		return container;
	}
}

// By default, the control will appear in the top left corner of the
// map with 0 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, -30));
}




function createMarkerElement(point, html, iconeElem, map, panto){
	var markerElement = new GMarker(point, {icon:iconeElem, title: f6_googlemaps_markers_click} );
	GEvent.addListener(markerElement, "click", function() { 
		setTimeout(function(){
			markerElement.openInfoWindowHtml(html); 
		},500);
		if(panto){
			map.panTo(point);
		}
	});
	return markerElement;
}



function proximiteMap(longitude, latitude, json){
	var notToFar = [];
    var allOffresDisney = getjsonGeneralGmap();
	
	$(allOffresDisney.googlemaps.offre).each(function (i, el){
		var dist = get_distance(longitude, latitude, el.longitude, el.latitude);
		if( dist <= 500 && dist >= 0){
            //console.log(dist)
            var newEl = el;
            newEl.dist = dist;
			notToFar.push(newEl);
		};
	});
    notToFar.sort(function(a,b){
        if(a.dist < b.dist){
            return -1;
        }else if(a.dist == b.dist){
            return 0;
        }else{
            return 1;
        }
    });
    var mapProxi = getMapProxi();
    mapProxi.clearOverlays();
    var newJsonProxi = {
        googlemaps:{
            langue:'fr',
            offre:[]
        }
    };
    var markerBounds = new GLatLngBounds();
    for(var newi = 0 ; newi <6; newi++){
        newJsonProxi.googlemaps.offre.push(notToFar[newi]);
        var randomPoint = new GLatLng(notToFar[newi].longitude, notToFar[newi].latitude);
        markerBounds.extend(randomPoint);

    }
    //console.log(newJsonProxi);
    mapProxi.panTo(new GLatLng(longitude,latitude));
    mapProxi.setCenter(markerBounds.getCenter(), mapProxi.getBoundsZoomLevel(markerBounds)-1);
    addLittlePointsByJson(newJsonProxi,mapProxi);
    
}

function get_distance(lat1, lng1, lat2, lng2) {
  var earth_radius = 6378137;   // Terre = sphère de 6378km de rayon
  var PI = Math.PI;
  var rlo1 = (lng1*PI/180);
  rla1 = (lat1*PI/180);
  rlo2 = (lng2*PI/180);
  rla2 = (lat2*PI/180);
  dlo = (rlo2 - rlo1) / 2;
  dla = (rla2 - rla1) / 2;
  a = (Math.sin(dla) * Math.sin(dla)) + Math.cos(rla1) * Math.cos(rla2) * (Math.sin(dlo) * Math.sin(dlo));
  
  d = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return (earth_radius * d);
}

