var map;
var geocoder;
var marker_array = [];
var txt_arrray = [];

var GeoAddress = Class.create( {
	initialize: function( index, address )
	{
		this.index = index;
		this.address = address;
	},
	
	startSearching: function( geocoder )
	{
		geocoder.getLocations( 
			this.address, 
			this.showMarkerOnMap.bindAsEventListener( this ) 
		);
	},
	
	showMarkerOnMap: function( response )
	{

		if (!response || response.Status.code != 200){
			alert("Sorry, we were unable to geocode that address - showMarkerOnMap");
		} 
		else 
		{
			var place = response.Placemark[0],
				point = new GLatLng( place.Point.coordinates[1], place.Point.coordinates[0] );
				
			if( this.index === 0 )
				map.setCenter( point, 13 );
					
			var pic = new GIcon(G_DEFAULT_ICON);
	        pic.image = '/typo3conf/ext/components/res/icons/googlemap_markers/' + this.index + '.png';
			pic.iconSize = new GSize(25, 35);

		    var marker = new GMarker(point, { icon : pic }),
				text = place.address;
			
			map.addOverlay(marker);
			
			marker_array[ this.index ] = marker;
			txt_arrray[ this.index ] = text;  
			
			GEvent.addListener(marker, "click", function() {			
		    	onMarkerClick( marker, text );
			});
		}
	}
});

// On page load, call this function
function loadGoogleMapsExtension(id)
{
	// create map object
	map = new GMap2(document.getElementById(id));
	var customUI = map.getDefaultUI(),
		addressStack = [];
    
	map.setUI(customUI);
	map.clearOverlays();
	
	// create geocoder object
	geocoder = new GClientGeocoder();
		
	// 1) show markers on map (json_result is a global variable, written by php)		
	result = json_result.evalJSON();
	for( var i=0, count = result.length; i<count; ++i ){

		var cur_street = result[i].street,
			cur_zip = result[i].zip,
			cur_city = result[i].city;
			search_address = cur_street + " " + cur_zip + " " + cur_city + " Deutschland",
			stack_index = addressStack.length;

		addressStack[ stack_index ] = new GeoAddress( i, search_address );
		addressStack[ stack_index ].startSearching( geocoder );	

	}

}

// marker click event
function onMarkerClick( p_marker, p_text)
{
	p_marker.openInfoWindowHtml( p_text );
}

// show location
function showLocation(i){
	marker_array[i].openInfoWindowHtml( txt_arrray[i] );
}

if($('googleMapsExtension')){			
	loadGoogleMapsExtension('googleMapsExtension');
	window.onunload = GUnload;
}