var mapPoint = null;
var markersPointArray = [];
var markerAddress = null;
var currentDepartement = null;
var initLatitude = 44.700901;
var initLongitude = -1.144753;
var initZoom = 11;
var forceLatitude = 44.640323;
var forceLongitude = -1.10693;
var forceZoom = 0;
var geocoder;
var map;
var defaultAddresse = 'Votre adresse';
/**
* variables propres Ã  l'affichage des fichiers KML
*/
var kml_max_indice = 6; 		// A  modifier lors de l'ajout de nouveau fichiers KML
var kml_nb_max_point = 1000; 	// nb maximum de point par fichier

$j(document).ready(function(){
	
	if($j('#map_canvas').length>0){
		forceZoom = initZoom;
		mapPoint = initializeGoogleMap('map_canvas', initLatitude, initLongitude, initZoom);
		initListPointMap(0);
	}
	if ($j('#contener_gmap_transport').length>0){
		mapPoint = initializeGoogleMap('contener_gmap_transport', initLatitude, initLongitude, initZoom);
		initListPointMap(5);
	}
	if ($j('#contener_gmap_baia').length>0){
		mapPoint = initializeGoogleMap('contener_gmap_baia', initLatitude, initLongitude, initZoom);
		initListPointMap(2);
	}
	if ($j('#contener_gmap_verre').length>0){
		mapPoint = initializeGoogleMap('contener_gmap_verre', initLatitude, initLongitude, initZoom);
		initListPointMap(3);
	}
	if ($j('#contener_gmap_decheteries').length>0){
		mapPoint = initializeGoogleMap('contener_gmap_decheteries', initLatitude, initLongitude, initZoom);
		initListPointMap(4);
	}
	if ($j('#map_canvas_global').length>0){
		mapPoint = initializeGoogleMap('map_canvas_global', initLatitude, initLongitude, initZoom);
		initAllPointMap(0);
	}
	
	geocoder = new google.maps.Geocoder();
});


/**
 * Init de la Google map
 */
function initializeGoogleMap(elemtId, lat, long, zoomInd) {
	
	/* Init de la carte centrÃ© sur la france */
	var latlng = new google.maps.LatLng(lat, long);
	var myOptions = {
		zoom: zoomInd,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.HYBRID,
		disableDefaultUI: false
	};
	map = new google.maps.Map(document.getElementById(elemtId), myOptions);
	
	/* Creating a bound zone */
	map.bounds = new google.maps.LatLngBounds ();
	
	return map;	
}

function centerMap(){
	if(document.getElementById("addressMap")){
		if(document.getElementById("addressMap").value == '' ||  document.getElementById("addressMap").value == defaultAddresse ){
			doCenterMap();
		}else{
			codeAddress();
		}
	}else{
		doCenterMap();
	}
}

function doCenterMap(){
	if(forceZoom > 0){
		/* On recentre la carte sur Arcachon */
		var localisation = new google.maps.LatLng(forceLatitude, forceLongitude);
	  	mapPoint.setCenter(localisation);
	 	mapPoint.setZoom(forceZoom);
		
	}else if(markersPointArray.length>0){
	   /* On recentre la carte de faÃ§on a voir tout les points de la carte */
	  mapPoint.fitBounds(mapPoint.bounds);
	  
	}else{
	  /* On recentre la carte sur l'origine */
		var localisation = new google.maps.LatLng(initLatitude, initLongitude);
	  	mapPoint.setCenter(localisation);
	 	mapPoint.setZoom(initZoom);
	}

}
/**
 * init de la liste des points correspondant Ã  1 type de fichier kml
 */
function initListPointMap(kml_file_indice){
	deleteOverlaysPoint();
	mapPoint.bounds = new google.maps.LatLngBounds ();
	
	/* Chargement et ajout des points sur la carte Ã  partir d'un JSON */
	$j.ajax({
	  url: '/index/list-marker?file_indice=' + kml_file_indice,
	  dataType: 'json',
	  contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
	  success: function(data){
		  
		  /* Ajout des points de la map */
		  
		  //permet gÃ©rer jusqu'Ã  'kml_nb_max_point' points pour chaque fichier JSON
		  j = kml_file_indice * kml_nb_max_point; 

		  for(var i=0 ; i<data.points.length; i++){
			addMarker(data.points[i],j);
			j++;
		  }
		  centerMap();
	  }
	});
}

/**
 * init de la liste des points correspondant Ã  tous les types de fichiers kml
 */

function initAllPointMap(show_kml){
	deleteOverlaysPoint();
	mapPoint.bounds = new google.maps.LatLngBounds ();
	
	/* Chargement et ajout des points sur la carte Ã  partir des JSON */
	$j.ajax({
	  url: '/index/all-marker',
	  dataType: 'json',
	  contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
	  success: function(data){
		  
		  j0 = 0;	  
		  j1 = 1 * kml_nb_max_point;	  
		  j2 = 2 * kml_nb_max_point;  
		  j3 = 3 * kml_nb_max_point;  
		  j4 = 4 * kml_nb_max_point; 
		  j5 = 5 * kml_nb_max_point;  
		  j6 = 6 * kml_nb_max_point;  
		  
		  for(var i=0 ; i<data.points.length; i++){
			
			if(data.points[i]['file_indice'] == 0){
				addMarker(data.points[i],j0);
				j0++;
			}else if(data.points[i]['file_indice'] == 1){
				addMarker(data.points[i],j1);
				j1++;
			}else if(data.points[i]['file_indice'] == 2){
				addMarker(data.points[i],j2);
				j2++;
			}else if(data.points[i]['file_indice'] == 3){
				addMarker(data.points[i],j3);
				j3++;
			}else if(data.points[i]['file_indice'] == 4){
				addMarker(data.points[i],j4);
				j4++;
		  	}else if(data.points[i]['file_indice'] == 5){
				addMarker(data.points[i],j5);
				j5++;
		  	}else if(data.points[i]['file_indice'] == 6){
				addMarker(data.points[i],j6);
				j6++;
			}
			
		  }
		  
		  for(i=0 ; i <= kml_max_indice ; i++){
			  if(i != show_kml){
			  	hideListPointMap(i);
			  }
		  }
		  centerMap();
	  }
	});
}


/**
* affiche les marqueurs correspondants Ã  une liste de points
*/
function showListPointMap(kml_file_indice){
	
	/* affiche une liste de points sur la carte Ã  partir d'un JSON */
	$j.ajax({
	  url: '/index/list-marker?file_indice=' + kml_file_indice,
	  dataType: 'json',
	  contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
	  success: function(data){
		   /* lss points  concernÃ©s de la map */   
		  s = kml_file_indice * kml_nb_max_point; //start point
		  e = s + (kml_nb_max_point -1); //end point

		  for(var i=s ; i<e; i++){
			  if(markersPointArray[i]){
				markersPointArray[i].setMap(mapPoint);
			  }
		  }
		  centerMap();
	  }
	});
}

/**
*	cache les marqueurs correspondants Ã  une liste de points
*/
function hideListPointMap(kml_file_indice){
	
	/* cache une liste de points sur la carte Ã  partir d'un JSON */
	$j.ajax({
	  url: '/index/list-marker?file_indice=' + kml_file_indice,
	  dataType: 'json',
	  contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
	  success: function(data){
		   /* Suppression des points de la map */   
		  s = kml_file_indice * kml_nb_max_point; //start point
		  e = s + (kml_nb_max_point -1); //end point

          for(var i=s ; i<e; i++){
			if(markersPointArray[i]){
				markersPointArray[i].setMap(null);
			}
		  }
	  }
	});
}

/**
 * Creation d'un marqueur
 */
function addMarker(poseur,indice){
	
	var latlng = new google.maps.LatLng(poseur['latitude'], poseur['longitude'])
	
	var myInfoWindow = new google.maps.InfoWindow({
		content: poseur['info'],
	});
	
	var iconImg = '/picto_gmap_cobas.png';

	if(poseur['file_indice'] == 0){
		iconImg = '/picto_gmap_cobas.png';
	}else if(poseur['file_indice'] == 1){
		iconImg = '/picto_gmap_bus.png';
	}else if(poseur['file_indice'] == 2){
		iconImg = '/picto_gmap_baia.png';
	}else if(poseur['file_indice'] == 3){
		iconImg = '/picto_gmap_verre.png';
	}else if(poseur['file_indice'] == 4){
		iconImg = '/picto_gmap_decheterie.png';
	}else if(poseur['file_indice'] == 5){
		iconImg = '/picto_gmap_bus_scolaires.png';
	}else if(poseur['file_indice'] == 6){
		iconImg = '/picto_gmap_sport.png';
	}
	
	
	var marker = new google.maps.Marker({
		position: latlng,
		map: mapPoint,
		title:poseur['type'] +' : ' + poseur['name'],
		id:poseur['id'],
		infoWindow:myInfoWindow,
		icon: iconImg
	});
	
	google.maps.event.addListener(marker, 'click', function() {
		//clearAllWindowInfo();
		this.infoWindow.open(mapPoint, this);
		//displayListPoint(this.id);
	});
	
	mapPoint.bounds.extend(marker.position);
	
	google.maps.event.addListener(marker, 'mouseout', function() {
		this.infoWindow.close();
	});
	
	markersPointArray[indice]=marker;
}

/**
 * Masque toutes les fenetres d'information des points
 */
function clearAllWindowInfo(){
	if (markersPointArray.length > 0) {
		for (var i in markersPointArray){
		   markersPointArray[i].infoWindow.close();
		}
	}
}

/**
 * Cache les marqueurs
 */
function clearOverlaysPoint() {
  if (markersPointArray.length > 0) {
	for (var i in markersPointArray){
		   markersPointArray[i].setMap(null);
	}
  }
}

/**
 * Affiche les marqueurs
 */
function showOverlaysPoint() {
  if (markersPointArray.length > 0) {
	for (var i in markersPointArray){
		   markersPointArray[i].setMap(mapPoint);
	}
  }
}

/**
 * Suppresion des marqueurs
 */
function deleteOverlaysPoint() {
  if (markersPointArray.length > 0) {
	for (var i in markersPointArray){
		   markersPointArray[i].setMap(null);
	}
    markersPointArray.length = 0;
  }
}

/**
*	Recherche d'une adresse et pose du marker correspondant
*/
function codeAddress() {
	var addressMap = document.getElementById("addressMap").value;
	if(addressMap !='' && addressMap != defaultAddresse){
		geocoder.geocode( { 'address': addressMap}, function(results, status) {
						   if (status == google.maps.GeocoderStatus.OK) {
							   	var latLng = results[0].geometry.location;
							   	markerAddress = new google.maps.Marker({
										map: map,
										position: results[0].geometry.location
									});

							   	map.setCenter(latLng);
							  	map.setZoom(16);
						   } else {
								alert("La localisation de votre adresse n'a pu etre determinee");
						   }
		});
	}else{
		if(markerAddress){
			markerAddress.setMap(null);
			centerMap();
		}
	}
}


