var IceCodeGMaps = { 
	container : null,
	map : null,
	zoom : 5,
	mapTypeId : google.maps.MapTypeId.ROADMAP,
	mapCenter : new google.maps.LatLng(41.85056479795757,13.230296875000004),
	markerLocations : new Array(), 
	markersContainer : new Array(),
	markerShadow: null,
	ajaxRequest: null,
	currentGoogleMapsWindow: false,
	bDynamicMarkers: true,

	setCenter: function(nLat,nLng) {
		this.mapCenter = new google.maps.LatLng(nLat, nLng);
	},

	setZoom: function(nZoom) {
		this.zoom = nZoom;
	},

	setStaticMarker : function(sBaloon, nLatitude, nLongitude) { 
		this.bDynamicMarkers = false; 
		this.setCenter(nLatitude, nLongitude); 
		this.markerLocations.push(new Array(sBaloon, nLatitude, nLongitude, 1));
	}, 

	setStaticDefaultCenterMarker : function() { 
		/* to do, non funziona attualmente...*/ 
		var marker = new google.maps.Marker({	position: this.mapCenter,  
												map: this.map, 
												title: "Punto di Partenza" 
											});   
	}, 

	drawMap : function(container) {
		if(typeof container == "string") {
			this.container = document.getElementById(container);
		} else {
			this.container = container;
		}

		var googleMapsOptions = {
			zoom: this.zoom,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
			mapTypeId: this.mapTypeId
		};

		this.map = new google.maps.Map(this.container, googleMapsOptions);
		this.map.setCenter(this.mapCenter, this.zoom);
		//this event tell us that all the map object are done!

		if(this.bDynamicMarkers) { 
			google.maps.event.addListener(this.map,'tilesloaded', function() {
				IceCodeGMaps.cleanMarkers();
				IceCodeGMaps.fetchMarkers();
			}); 

			google.maps.event.addListener(this.map, 'dragend', function() {
				IceCodeGMaps.cleanMarkers();
				IceCodeGMaps.fetchMarkers();
			});

			google.maps.event.addListener(this.map, 'zoom_changed', function() {
				IceCodeGMaps.cleanMarkers();
				IceCodeGMaps.fetchMarkers();
			});
		}

		this.setMarkers();
	},

	fetchMarkers : function() {
		try {
			var bounds = this.map.getBounds();
		} catch (e) {
			//  console.log("ECEZIONE: " + e);
		}

		this.ajaxRequest= new Ajax( ABSOLUTE_PATH + 'geoPharmacy.html', 'GET');
		this.ajaxRequest.setData("from="+bounds.getNorthEast().toUrlValue()+"&to="+bounds.getSouthWest().toUrlValue()+"&type="+ this.getMapType());
		if(this.ajaxRequest.sendRequest(false) && this.ajaxRequest.getResponse() != "FAIL") {
			var xml = getXMLDOM(this.ajaxRequest.getResponse());
			var nodeResultGroup = xml.getElementsByTagName('marker');
			if(nodeResultGroup.length > 0) {
				for(var counter = 0; counter < nodeResultGroup.length && counter < 20; counter++) {
					var sHtmlMarker =  getTextContent(nodeResultGroup[counter].getElementsByTagName('baloon')[0]);

					var aNewLocation = new Array (	sHtmlMarker,
													nodeResultGroup[counter].getAttribute('lat'),
													nodeResultGroup[counter].getAttribute('long'),
													this.zoom, 
													nodeResultGroup[counter].getAttribute('count'),
													nodeResultGroup[counter].getAttribute('name')
													);
					this.markerLocations.push(aNewLocation);
				}
			this.setMarkers();
			}
		} else {
			//console.log("ERRORE RICHIESTA");
		}
	},
	
	setMarkers: function (bCenter) {
		if(typeof(bCenter) === undefined) {
			bCenter = true;
		}
		var maxLog = -180.00;
		var maxLat = -90.00;
		var minLog = 180.00;
		var minLat = 90.00;
		var location = this.markerLocations;
		for (var i = 0; i < location.length; i++) {
			if(location[i][4] != "" && location[i][4] > 0) {
				var nMarkerWidth = 36 + (10* ( 1 + parseInt((Math.log(location[i][4]) / Math.log (10)))));
				var image = this.getMarker(ABSOLUTE_PATH + 'maps/markers/marker'+location[i][4]+'.png', nMarkerWidth, 40);

			} else {
				var image = this.getMarker(ABSOLUTE_PATH + 'maps/markers/marker.png', 20, 34);
			}
			this.createMarker(location[i], image);
			maxLat = Math.max(maxLat, location[i][1]);
			maxLog = Math.max(maxLog, location[i][2]);
			minLat = Math.min(minLat, location[i][1]);
			minLog = Math.min(minLog, location[i][2]);
		}
		//Centro la mappa
		if(bCenter) {
			this.map.setCenter( new google.maps.LatLng((maxLat + minLat) / 2, (maxLog + minLog) / 2), this.zoom);
		}
	},

	getMarker : function(sImageUrl, width, height) {
		return new google.maps.MarkerImage(sImageUrl, 
											new google.maps.Size(width, height), 
											new google.maps.Point(0,0), 
											new google.maps.Point(0, height)
											);
	},

	createMarker: function (location, image) {
		var infoWindow = new google.maps.InfoWindow({content: location[0]});

		var marker = new google.maps.Marker({
												position: new google.maps.LatLng(location[1], location[2]),
												map: this.map,
												shadow: this.markerShadow,
												icon: image,
												zIndex: location[3]
											});
		google.maps.event.addListener(marker, 'click', function () {
															if (IceCodeGMaps.currentGoogleMapsWindow) {
																IceCodeGMaps.currentGoogleMapsWindow.close();
															}
															IceCodeGMaps.currentGoogleMapsWindow = new google.maps.InfoWindow({
															content: location[0]
															});
															IceCodeGMaps.currentGoogleMapsWindow.open(this.map, marker);
										});
		this.markersContainer.push(marker);
	},

	cleanMarkers: function () {
		for(var i = 0; i < this.markersContainer.length; i++) {
			this.markersContainer[i].setMap(null);
		}

		this.markersContainer = Array();
		this.markerLocations = Array();
	},

	getMapType: function(){
		if(this.map.zoom < 7) return 'administrative_area';
		else if(this.map.zoom < 9) return 'sub_administrative_area';
		else if(this.map.zoom < 12) return 'locality';
		else return 'pharmacy';
	},

	initRoutePlanner : function () { 
		this.directionsDisplay = new google.maps.DirectionsRenderer(); 
		this.directionsService = new google.maps.DirectionsService(); 
		this.directionsDisplay.setMap(this.map); 
		document.getElementById("route").innerHTML = ''; 
		this.directionsDisplay.setPanel(document.getElementById("route")); 
	}, 

	routeToAddress : function() { 
		var sLatLng = this.mapCenter.lat()+ "," + this.mapCenter.lng(); 
		var request = { 
				origin: document.getElementById('address').value + " " + document.getElementById('place').value+' Italia', 
				destination: sLatLng, 
				travelMode: google.maps.DirectionsTravelMode.DRIVING, 
				region: 'it', 
				unitSystem: google.maps.DirectionsUnitSystem.METRIC 
				}; 
		 
		var directionsDisplay = this.directionsDisplay; 
		var map = this.map; 
	 
		this.directionsService.route(request, function(response, status) { 
													if (status == google.maps.DirectionsStatus.OK) { 
														directionsDisplay.setDirections(response); 
														directionsDisplay.setMap(map); 
														IceCodeGMaps.cleanMarkers(); 
														document.getElementById('errorContainer').innerHTML = ""; 
													} else { 
														directionsDisplay.setMap(null); 
														document.getElementById("route").innerHTML = ""; 
														if(status=="NOT_FOUND") { 
																document.getElementById('errorContainer').innerHTML = "Attenzione, inserisci l'indirizzo correttamente."; 
														} else { 
																document.getElementById('errorContainer').innerHTML = "Errore generico,si prega di riprovare."; 
														} 
													} 
										}); 
	}
}//end of object

