var dealersMap = null;
var categories = [ ];
var centreMap = [ ];
var zoomLevel = 7;
var markers = [ ];
var markerOptions = { };

centreMap['lat'] = 53.30462107510271;
centreMap['lng'] = -0.37353515625;

$(document).ready(function() {
	if (GBrowserIsCompatible()) {

		// Bind 'change' event to the countries drop down
		$('select#dealerCountries').bind(
			'change',
			function() {
				var country = dealerCountries[this.value];

				var point = new GLatLng(
					country['latitude'],
					country['longitude']
				);

				// Focus on the selected country
				dealersMap.setCenter(point, parseInt(country['zoom_level']));

				// Clear all existing maps
				dealersMap.clearOverlays();

				// Add this county's markers
				if(markers[this.value]) {
					for(x=0; x<markers[this.value].length; x++) {
						dealersMap.addOverlay(markers[this.value][x]);
					}
				}
			}
		);

		// Marker Icon
		var baseIcon = new GIcon();
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        baseIcon.infoShadowAnchor = new GPoint(18, 25);

		var househamIcon = new GIcon(baseIcon);
		househamIcon.image = '/images/green_map_marker.png';

		// Marker options
		markerOptions = { icon:househamIcon };

		// Load default country detail
		country = dealerCountries[$('select#dealerCountries')[0].value];

		// Create & Setup Google Map
		dealersMap = new GMap2(document.getElementById('dealers_map'));
		dealersMap.setCenter(new GLatLng(
				parseInt(country['latitude']),
				parseInt(country['longitude'])
			),
			parseInt(country['zoom_level'])
		);
		dealersMap.addControl(new GLargeMapControl());
		dealersMap.addControl(new GMapTypeControl());

		// Download all the marker info
		GDownloadUrl("/dealer_markers.xml.php", function(doc) {
	        var xmlDoc = GXml.parse(doc);
	        var xmlMarkers = xmlDoc.getElementsByTagName("marker");


	        // Loop through all the markers in the XML document
	        for (var i = 0; i < xmlMarkers.length; i++) {

	        	// Create the marker
	          	var thisMarker = createMarker(xmlMarkers[i]);

	          	// Store the marker for later use
	          	categories.push(thisMarker.myCategory);
	          	if(!markers[thisMarker.myCategory]) {
					markers[thisMarker.myCategory] = new Array( );
	          	}
	          	markers[thisMarker.myCategory].push(thisMarker);
	        }

	        $('select#dealerCountries').trigger('change');
		});
	}
});


function loadMarkers() {
	var markers = [ ];
	$(markerData).each(function(index, data) {
		markers.push(new GMarker(new GLatLng(data.latitude, data.longitude), { }));
	});
	markerCluster = new MarkerClusterer(dealersMap, markers);
}


function createMarker(xml) {
	var marker = new GMarker(
		new GLatLng(
		    parseFloat(xml.getAttribute("lat")),
		    parseFloat(xml.getAttribute("lng"))
		),
		markerOptions
	);

	marker.myName = 	xml.getAttribute("name");
	marker.myUrl =		xml.getAttribute("url");
	marker.myTelephone =xml.getAttribute("telephone");
	marker.myEmail = 	xml.getAttribute("email");
	marker.myCategory = xml.getAttribute("category");
	marker.myAddress = 	xml.getElementsByTagName("address")[0].childNodes[0].nodeValue;
	marker.myHtml =
	    "<p style=\"margin-bottom:0\"><strong>"+marker.myName+"</strong></p>"
	    +marker.myAddress
	;

	if(marker.myTelephone!='' || marker.myEmail!='' || marker.myUrl!='') {
		marker.myHtml+= "<br />";
	}
	if(marker.myTelephone != '') {
		marker.myHtml+= "<br /><strong>Telphone:</strong>&nbsp;"+marker.myTelephone;
	}
	if(marker.myEmail != '') {
		marker.myHtml+= "<br /><strong>Email:</strong>&nbsp;<a target='_blank' href='mailto:"+marker.myEmail+"'>"+marker.myEmail+"</a>";
	}
	if(marker.myUrl != '') {
		marker.myHtml+= "<br /><strong>Web:</strong>&nbsp;<a target='_blank' href='"+marker.myUrl+"'>"+marker.myUrl+"</a>";
	}

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(marker.myHtml);
	});

	return marker;
}