// $Id: maputils.js,v 1.7 2006-05-07 12:48:11 lor Exp $
//
// (C) 2006 Lorenzo Colitti <lorenzo at colitti.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

function markerHTML(place) {
	var where = place[2];
	var when = place[3];
	var imgURL = place[4];
	var linkURL = place[5];

	// Hack: fire off image load now, so when marker window is opened the
	// browser already knows the size of the image and the balloon comes
	// up the right size
	var img = new Image();
	img.src = imgURL;

	var html = '<div align="center"><b>' + where + '</b><br>' + when;
	if(imgURL && linkURL)
		html += '<br><a href="' + linkURL +'"><img src="' + imgURL + '"></a>';
	html += '</div>';

	return html;
}

function createMarker(map, place) {
	var lng = place[0];
	var lat = place[1];
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point);
	var html = markerHTML(place);
//	GEvent.addListener(marker, 'doubleclick', function() { map.setCenter(point) });
	GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });
	return marker;
}

function testAPI() {
	try {
		return GBrowserIsCompatible();
	} catch(e) {
		return false;
	}
}

function makeMap(mapDiv) {
	var map = new GMap2(mapDiv);
	mapDiv.map = map;
	map.container = mapDiv;

	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());

	map.setCenter(new GLatLng(20, 0), 2);
	map.setMapType(G_HYBRID_MAP);

	mapDiv.updateXY = function() {
		var center = this.map.getCenter();
		var form = document.getElementById("XYform");
		if(form) {
			if(form.lat) form.lat.value = center.lat();
			if(form.lng) form.lng.value = center.lng();
		}
	}

	mapDiv.center = function() {
		var form = document.getElementById("XYform");
		if(form && form.lat && form.lat.value && form.lng && form.lng.value)
			this.map.setCenter(new GLatLng(form.lat.value, form.lng.value), 3);
	}

	mapDiv.setMarkers = function(places) {
		this.map.clearOverlays();
		for(var i = 0; i < places.length - 1; i++) {
			var place = places[i];
			var marker = createMarker(this.map, place);
			this.map.addOverlay(marker);
		}
	}

	mapDiv.loadMarkers = function() {
		var map = this;
		var request = GXmlHttp.create();
		request.open('GET', 'places.js.php', true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				var script = request.responseText;
				eval(script);
				map.setMarkers(places);
			}
		}
		request.send(null);
	}

	GEvent.addListener(map, 'moveend', function() { this.container.updateXY(); });
}
