var map;
var geocoder;
var marker_array = [];
var txt_arrray = [];

function GeoAddress(){
	
	this.initialize = function( index, address, icon )
	{
		this.index = index;
		this.address = address;
		this.icon = icon;
	},
	
	this.startSearching = function( geocoder )
	{
		geocoder.getLocations( 
			this.address, 
			$.proxy( this.showMarkerOnMap, this )
		);
	},
	
	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/mmsdd_partner/Resources/Public/Icons/Google/' + ( this.icon ) + '.png';
			pic.iconSize = new GSize(24, 36);

		    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 = eval( json_result );
	for( var i=0, count = result.length; i<count; ++i ){

		var cur_count = result[i].count,
			cur_street = result[i].street,
			cur_zip = result[i].zip,
			cur_city = result[i].city;
			search_address = cur_street + " " + cur_zip + " " + cur_city,
			stack_index = addressStack.length;

	    var geoAddress = new GeoAddress();
	    geoAddress.initialize( i, search_address, cur_count );
		addressStack[ stack_index ] = geoAddress;
		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( document.getElementById( 'googleMapsExtension' ) ){			
	loadGoogleMapsExtension( 'googleMapsExtension' );
	window.onunload = GUnload;
}
