var map = null;
var geocoder = null;
var baseIcon = null;
var mapControl = null;

function initialize()
{
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"), { size: new GSize(680, 400) });
		map.setCenter(new GLatLng(47.635784,13.590088), 7);
		geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode('.de');

		// Initialise Base marker
		baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "http://cesar.lsweb.at/wp-content/plugins/mappress-google-maps-for-wordpress/images/cesarlogo_small.png";
		baseIcon.iconSize = new GSize(50, 30);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);

		// Initialise Zoom control
		map.addControl(new GLargeMapControl3D());
 		map.enableScrollWheelZoom();
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
	}
}

function markAddressArray(coordinates)
{
	if (geocoder) {
		for (var i=0; i<coordinates.length; i++) {
			var coordinate = coordinates[i];
			markAddress(coordinate.text, coordinate.latitude, coordinate.longitude);
		}
	}
}

function markAddress(text, latitude, longitude)
{
	if (geocoder) {
		var marker = new GMarker(new GLatLng(latitude, longitude), { icon: baseIcon });
		GEvent.addListener(marker, 'click', function() {
			// When clicked, open an Info Window
			marker.openInfoWindowHtml('<h1>' + text.title + '</h1><br /><br />'
				+ '<address>'
				+ '<strong>Adresse:</strong> ' + text.address + '<br />'
				+ '<strong>PLZ/Ort:</strong> ' + text.suburb + '<br />'
				+ '<strong>Telefon:</strong> ' + text.phone + '<br />'
				+ '<strong>Email:</strong> ' + text.email + '<br />'
				+ '<strong>Website:</strong> ' + text.website + '<br />'
				+ '</address>'
			);
		});
		map.addOverlay(marker);
	}
}

function showAddress(address, element) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					map.setCenter(point, 15);
					var marker = new GMarker(point, { icon: baseIcon });
					map.addOverlay(marker);
					marker.openInfoWindowHtml(address);
				}
		});
		// Searching for current position
		var coords = eval(findPos(element));

		// Apply CSS ;)
		var mapElement = document.getElementById('map_wrap');
		mapElement.style.display = 'block';
		mapElement.style.position = 'absolute';
		mapElement.style.left = (coords.left - 500) + 'px';
		mapElement.style.top = (coords.top + 20) + 'px';
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return { left: curleft, top: curtop };
}