var map;
var id;
var latlngs = [];
  
function getCenterAndZoom() {
	
	var viewSize = GSize(600,450);
	var bounds = new GLatLngBounds();
	
	for (id in markers) {
		var point = new GLatLng(markers[id].latitude, markers[id].longitude);
		bounds.extend(point);
	}
	
	var viewSize = GSize(600,450);
	var newZoom = map.getBoundsZoomLevel(bounds,viewSize);
	
	var centLat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
	var centLng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
	
	return [centLat, centLng, newZoom];
}

function writeText(id, point) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";
	listItemLink.innerHTML = markers[id].comments;
	
	var focusPoint = function() {
		map.panTo(point);
		return false;
	}
	
	listItemLink.onclick = focusPoint;
	
	document.getElementById('sidebar_list').appendChild(listItem);

}

function updateCenter() {
 	map.clearOverlays();
	var icon = new GIcon();
	icon.image = './images/maps/red.JPG';
	icon.iconSize = new GSize(3,3);
	icon.iconAnchor = new GPoint(1,1);
	var marker = new GMarker(map.getCenter(),icon);
	map.addOverlay(marker);
	
	var polyline = new GPolyline(latlngs, 'YELLOW', 6, 0.5)
	map.addOverlay(polyline);
}

function init() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		var caz = getCenterAndZoom();
		map.setCenter(new GLatLng(caz[0], caz[1]), caz[2]);
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		 
		for(id in markers) {
 			latlngs.push(new GLatLng(markers[id].latitude, markers[id].longitude));
 			writeText(id, latlngs[id]);
		}
		
		updateCenter();
		
		GEvent.addListener(map,'moveend',function() {
			updateCenter();
		});
		
		// The Event handlers for Zoom at Cursor on Scroll 
      	GEvent.addListener( this.map, 'mousemove', function(point) { 
        	mouselat = point.y.toFixed(6); 
        	mouselng = point.x.toFixed(6); 
      	}); 
      	GEvent.bindDom( this.div, 'DOMMouseScroll', this, this.onScroll 
		); //Firefox 
		GEvent.bindDom( this.div, 'mousewheel', this, this.onScroll ); // 
		IE + Opera 
		// End of Event handlers for Zoom at Cursor on Scroll 

		
	}
}

 
window.onload = init;
window.onunload = GUnload;
