
window.addEvent('unload', function () {
	if (map.id) {
		GUnload();
	}
});

window.addEvent('load', function () {
	if (map.id) {
		var options = {zoom: 10};
		if (map.points.length > 0) {
			var coords = map.points[0].location.split(',');
			options.coords = {
				x: coords[0],
				y: coords[1]
			}
		}
		map.map = new GoogleMapper(map.id, options);
		map.points.each(function (point) {
			map.map.addPoint(point.location, point.title, point.html);
		});
	}
});


var map = {
	id: '',
	map: null,
	points: []
}
function loadMap(id, points) {
	map.id = id;
	map.points = points;
}
function addPoint(point) {
	if (point) {
		map.points.push(point)
	}
}


var GoogleMapper = new Class({
	elMap: null,
	elField: null,
	map: null,
	point: null,
	marker: null,
	points: [],
	icon: null,
	options: {
		coords: {
			x: 52.522906,
			y: -1.845703
		},
		zoom: 6
	},
	initial: {
		options: {},
		value: ''
	},
	initialize: function (map, options) {
		if (!GBrowserIsCompatible()) {
			return;
		}
		this.elMap = $(map);

		this.initial = {
			options: options || {}
		}
		this.reset();
	},
	reset: function () {
		// clear the id of it's contents
		this.elMap.empty();

		options = this.initial.options;
		this.point = null;

		this.setOptions(options);

		this.createMap();

		this.points.each(function (point) {
			this.addMarker(point);
		}, this);
	},
	addPoint: function (coords, title, content) {
		coords = coords.split(',');
		var point = new GLatLng(coords[0], coords[1]);
		this.points.push(point);
		this.addMarker(point, title, content);
	},
	addMarker: function (point, title, content) {
		var marker = new GMarker(point, {
			title: title,
			clickable: (content)
		});
		if (content) {
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(content);
			});
		}
		this.map.addOverlay(marker);
	},
	createMap: function () {
		var map = new GMap2(this.elMap);
		map.setCenter(new GLatLng(this.options.coords.x, this.options.coords.y), this.options.zoom);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		this.map = map;
	},
	deleteMarker: function () {
		this.map.removeOverlay(this.marker);
		this.point = null;
	},
	createMarker: function () {
		var marker = new GMarker(this.point, {
			icon:G_DEFAULT_ICON,
			draggable: true,
			zIndexProcess: function () {
				return 1;
			}
		});
		marker.enableDragging();

		GEvent.addListener(marker, 'drag', function() {
			this.elField.value = this.marker.getPoint().toUrlValue();
		}.bind(this));

		GEvent.addListener(marker, 'remove', function () {
			this.elField.value = '';
		}.bind(this));

		this.marker = marker;
		this.map.addOverlay(this.marker);
		this.map.setCenter(this.point, this.zoom);
		this.elField.value = this.marker.getPoint().toUrlValue();
	}
});
GoogleMapper.implement(new Options);
