var map = null;
var geocoder = null;
var json = [];
var point = null;

/*
 * This method initializes the map
 */
function initialize(map)
{
	map.setMapType(G_HYBRID_MAP);
	
	if (GBrowserIsCompatible())
	{
	//Display GLatLng info and zoom level
	GEvent.addListener(map, "click", function(overlay,latlng) {     
      if (latlng) {   
        var myHtml = "The GLatLng value is: " + map.fromLatLngToDivPixel(latlng) + "<br /><br />Zoom level " + map.getZoom();
        //map.openInfoWindow(latlng, myHtml);
      }
    });
	
	geocoder = new GClientGeocoder();
	}
}

/*
 * This method displays a specific address on the map
 */
function displayAddressmap(address, postcode, city, map, displayMarker, displayText, addressText)
{
	//Initialize the map
	initialize(map);
	
	//Scroll = Zoom
	map.enableScrollWheelZoom();
	
	//Zoom only when mouse in map area
	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll",
	function(oEvent) { if (oEvent.preventDefault)
	oEvent.preventDefault(); });
	
	//Define widespace
	if (postcode != "")
	{
		var showWidespace = " ";
	}
	else
	{
		var showWidespace = "";
	}
	
	//Define full search address
	var fullAddress = address + ', ' + postcode + showWidespace + city;
	
	//Define display address
	var displayAddress = '<b>' + addressText + ':</b><br />' + address + '<br />' + postcode + showWidespace + city;
	
	if (geocoder)
	{
		geocoder.getLatLng(fullAddress, function(point)
		{
			if (!point)
			{
				alert(fullAddress + " not found");
			}
			else
			{
				map.setCenter(point, 13);
				
				var marker = new GMarker(point);
				
				if (displayMarker)
				{
					map.addOverlay(marker);
					if (displayText)
					{
						marker.openInfoWindowHtml(displayAddress);
					}
				}
			}
		} );
	}
}

/*
 * This method displays markers for all the addresses selected from a specific type
 */
function generateLatAndLngArray(lat, lng, displayAddressArray)
{
	for (i = 0; i < lat.length; i++)
	{
		json[i]={'id': displayAddressArray[i], 'lat': + lat[i], 'lng': + lng[i] };
	}
}

var cluster;

function displayTypemap(gmapsArray)
{
	//Define array values
	lat 				= gmapsArray[0];
	lng				= gmapsArray[1];
	displayAddressArray 		= gmapsArray[2];
	clickToZoomText 		= gmapsArray[3];
	clickToGetInformationsText 	= gmapsArray[4];
	map				= gmapsArray[5];
	iconTypeidArray			= gmapsArray[6];
	iconExistsArray 		= gmapsArray[7];
	iconWidthArray 			= gmapsArray[8];
	iconHeightArray 		= gmapsArray[9];
	
	if (GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById('map_canvas'));
	}

	initialize(map);
	
	var marker, markersArray=[];
	
	//Generate lat and lng array from addressArray and insert it into the json array
	generateLatAndLngArray(lat, lng, displayAddressArray);
	
	
	
	// Get bounds to center view
	var latlngbounds = new GLatLngBounds( );
	
	for (var i=0; i<json.length; i++) {
		marker=newMarker(new GLatLng(json[i].lat, json[i].lng), json[i].id, clickToGetInformationsText, iconTypeidArray[i], iconExistsArray[i], iconWidthArray[i], iconHeightArray[i]);
		markersArray.push(marker);
	}
	
	// Center view
	map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
	
	map.setMapType(G_HYBRID_MAP);
	
	cluster=new ClusterMarker(map, { markers:markersArray }, clickToZoomText);
	cluster.fitMapToMarkers();
	
	map.savePosition();	//	enables the large map control centre button to return the map to initial view
	
	//	add an HtmlControl to enable toggling of the ClusterMarker cluster function
	//	see http://googlemapsapi.martinpearman.co.uk/htmlcontrol for more info on HtmlControl
	var html='<div class="htmlControl" style="padding:0px 3px 3px 3px">Enable clustering: <input type="checkbox" checked="checked" onclick="toggleClustering()" /></div>';
	//var control=new HtmlControl(html);
	//map.addControl(control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
	
	//Add small mapcontrol
	map.addControl(new GSmallMapControl());
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	
	//Scroll = Zoom
	map.enableScrollWheelZoom();
	
	//Zoom only when mouse in map area
	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll",
	function(oEvent) { if (oEvent.preventDefault)
	oEvent.preventDefault(); });
}

function newMarker(markerLocation, markerId, clickToGetInformationsText, imgid, imgExists, imgWidth, imgHeight)
{
	if (imgExists) //Change icon
	{
		// Create our "tiny" marker icon
		var customIcon = new GIcon(G_DEFAULT_ICON);
		customIcon.image = "/components/com_redlist/images/type_icons/" + imgid + ".png";
		customIcon.iconSize=new GSize(imgWidth, imgHeight);
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:customIcon, title:clickToGetInformationsText };
	}
	else //Show default icon
	{
		// Set up our GMarkerOptions object
		markerOptions = { title:clickToGetInformationsText };
	}
	
	var marker=new GMarker(markerLocation, markerOptions);
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(markerId);
	});
	return marker;
}

function toggleClustering() {
	cluster.clusteringEnabled=!cluster.clusteringEnabled;
	cluster.refresh(true);	//	true required to force a full update of the markers - otherwise the update would occur next time that the map is zoomed or the active markers change
}
