google.load("maps", "2.x");
google.setOnLoadCallback(initMap);

window.addEvent('unload', function() {
	new google.maps.Unload();
} );


function initMap()
{
	// initialize map engine
	m = new mapEngine();
	m.init();
}

function mapEngine()
{

	this.init = function()
	{
		this.maps = new Array();
		this.addMap( $("map") );
		
	},
	
	this.addMap = function( obj )
	{
		browserEngine.importRel( obj );
		obj.map = new Map( obj );
		
		this.maps[ this.maps.length ] = obj.map;
	}
}

var Map = new Class({
	initialize: function(el){
		this._el = el;
		this._map = new google.maps.Map2( this._el );
		if (el.lat > 0)
			var center = new google.maps.LatLng(el.lat, el.lng);
		else
			var center = new google.maps.LatLng(44.7577048448913, 10.6598281860352);
		this._map.setCenter(center, 12);
		var editable = ( (el.edit == 'true') ? true : false);
		this.marker = new google.maps.Marker( center, { 'draggable': editable } );
		if (editable)
		{
			new google.maps.Event.addListener(this.marker, "dragend", function(marker) {
				$('lat').value = this.marker.getLatLng().lat();
				$('lng').value = this.marker.getLatLng().lng();
			}.pass(this.marker,this) );
		}
		if ($('search-map'))
		{
			this.search = $('search-map');
			this.searchButton = $('search-button');
			this.geocoder = new google.maps.ClientGeocoder();
			this.searchButton.addEvent('click', function(e) {
				new Event(e).stop();
				this.geocoder.getLocations(this.search.value, this.parseSearch.bind(this) );
			}.bind(this) );
		}
		this._map.addOverlay( this.marker );
	},
	
	parseSearch: function( response )
	{
		if (!response || response.Status.code != 200) {
			alert("Sorry, we were unable to geocode that address");
		} else {
			place = response.Placemark[0];
			point = new google.maps.LatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			this._map.panTo(point);
			this.marker.setLatLng( point );
			$('lat').value = this.marker.getLatLng().lat();
			$('lng').value = this.marker.getLatLng().lng();
		}
	}
});

Map.implement(new Events, new Options);
