var map, manager;
var centerLatitude = 50.78697, centerLongitude = 0.305840, startZoom = 16;

function createMarkerClickHandler(marker, text, text2, link) {
	return function() {
		marker.openInfoWindowHtml(
			'<h3>' + text + '</h3>' + text2 + '<a>&nbsp;</a>'
		);
		return false;
	};
}

function createMarker(pointData) {
	var latlng = new GLatLng(pointData.latitude, pointData.longitude);
	var icon = new GIcon();
	icon.image = pointData.iconimage;
	icon.shadow = pointData.iconshadow;
	icon.iconSize = new GSize(pointData.wd, pointData.ht);
	icon.iconAnchor = new GPoint(pointData.iconmarkerx, pointData.iconmarkery);
	icon.infoWindowAnchor = new GPoint(25, 7);
	opts = {
		"icon": icon,
		"clickable": true,
		"labelText": pointData.abbr,
		"labelOffset": new GSize(pointData.labeloffsetx, pointData.labeloffsety)
	};
	var marker = new LabeledMarker(latlng, opts);
	var handler = createMarkerClickHandler(marker, pointData.name, pointData.wtxt, pointData.wp);
	
	GEvent.addListener(marker, "click", handler);

	//var listItem = document.createElement('li');
	//listItem.innerHTML = '<div class="label">'+pointData.abbr+'</div><a href="../mapping/' + pointData.wp + '">' + pointData.name + '</a>';
	//listItem.getElementsByTagName('a')[0].onclick = handler;
	//document.getElementById('sidebar-list').appendChild(listItem);
	return marker;
}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case. 
	return 0;
}

function handleResize() {
	var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 30;
	document.getElementById('map').style.height = height + 'px';
	//document.getElementById('sidebar').style.height = height + 'px';
}

function init() {
	//handleResize();
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	map.addControl(new GMapTypeControl());
	manager = new GMarkerManager(map);
	// This is a sorting trick, don't worry too much about it.
	markers.sort(function(a, b) { return (a.abbr > b.abbr) ? +1 : -1; }); 
	batch = [];
	for(id in markers) {
		batch.push(createMarker(markers[id]));
	}
	manager.addMarkers(batch, 11);
	manager.refresh();
}

//window.onresize = handleResize; If you allow handle re-size the map overflows its DIV.....
window.onload = init;
window.onunload = GUnload;

