var map, geocoder, cursearch, sidebar, bounds, center;

/* local search functions */

/* global search functions */

function load() {
	if (GBrowserIsCompatible()) {
		showLoader();
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById('map'));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	 	map.setCenter(new GLatLng(54.622978,-3.592773), 5);
	}
}

function searchLocations(address) {
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			alert(address + ' not found');
		} else {
			center = latlng;
			searchLocationsNear();
		}
	});
}

function searchLocationsNear() {
	var radius = 25;
	var searchUrl = xml_url + '&region=' + regionName  + '&radius=' + radius + '&_frameset=true'; // &lat=' + center.lat() + '&lng=' + center.lng() + '
 	// self.location = (searchUrl);
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();
		sidebar = document.getElementById('sidebar');
		sidebar.innerHTML = '';
		if (markers.length == 0) {
			 showMap();
			 sidebar.innerHTML = 'No pubs found.';
			 map.setCenter(new GLatLng(54.622978,-3.592773), 5);
			 return;
		}
		bounds = new GLatLngBounds();
		setm(markers, 0);
	});
}

function setm(markers, i) {
	name = markers[i].getAttribute('name');
	address = markers[i].getAttribute('address');
	telephone = markers[i].getAttribute('telephone');
	distance = parseFloat(markers[i].getAttribute('distance'));
	var postcode = markers[i].getAttribute('postcode');
	short_name = markers[i].getAttribute('short_name');
	letter = String.fromCharCode("A".charCodeAt(0) + i);
	cursearch = new GlocalSearch();
	cursearch.setSearchCompleteCallback(null, function() {
	 if (cursearch.results[0]) {		
		 var resultLat = cursearch.results[0].lat;
		 var resultLng = cursearch.results[0].lng;
		 var point = new GLatLng(resultLat, resultLng);
		 marker = createMarker(point, letter, name, address, telephone);
		 map.addOverlay(marker);
		 sidebarEntry = createSidebarEntry(marker, letter, name, address, telephone, distance, short_name);
		 sidebar.appendChild(sidebarEntry);
		 bounds.extend(point);
		 if ((markers.length - 1) == i) {
		 	iconsAndZoom();
		 } else {
			 i++;
			 if (markers[i]) {
				setm(markers, i);
			 }
		 }
	 } else  {
		 if (postcode != null) {
			 
		 }
	 }
	});
	cursearch.execute(postcode + ", UK");
}

function iconsAndZoom() 
{
		var homeIcon = new GIcon();
		homeIcon.shadow = "http://maps.google.com/mapfiles/arrowshadow.png";
		homeIcon.iconSize = new GSize(30, 34);
		homeIcon.shadowSize = new GSize(37, 34);
		homeIcon.iconAnchor = new GPoint(9, 34);
		homeIcon.infoWindowAnchor = new GPoint(9, 2);
		homeIcon.infoShadowAnchor = new GPoint(18, 25);
		
		var myHomeIcon = new GIcon(homeIcon);
		myHomeIcon.image = "http://maps.google.com/mapfiles/arrow.png";
		markerOptions = { icon:myHomeIcon };
		
		var homeMarker = new GMarker(center, markerOptions);
		map.addOverlay(homeMarker);
		
		var SW = bounds.getSouthWest();
		var NE = bounds.getNorthEast();
		var height = NE.lat() - SW.lat();
		var width = NE.lng() - SW.lng();
		// Set a 5% margin for left, right, and bottom, but 10% margin for top as markers are tall and need extra space
		var marginBounds = new GLatLngBounds(new GLatLng(SW.lat() - 0.05*height, SW.lng() - 0.05*width), new GLatLng(NE.lat() + 0.10*height, NE.lng() + 0.05*width) );
		map.setCenter(marginBounds.getCenter(),map.getBoundsZoomLevel(marginBounds));
		
		showMap();
		
		// 'Standard' way of setting zoom level doesn't always show all points clearly.
		//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function showLoader() {
	// document.getElementById('maploading').style.display = 'block';
}

function showMap() {
	// Hide loader
	// document.getElementById('maploading').style.display = 'none';
	// Show map and sidebar
	// document.getElementById('maphide').style.display = 'block';
	// document.getElementById('sidebarhide').style.display = 'block';
}


function createMarker(point, letter, name, address, telephone) {
	
	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);
	
		// Icon
		/* var icon = new GIcon();
		icon.image = "/static/images/layout/marker.png";
		icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		icon.iconSize = new GSize(16, 19);
		icon.shadowSize = new GSize(16, 19);
		icon.iconAnchor = new GPoint(16, 16);
		icon.infoWindowAnchor = new GPoint(16, 19); */

	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
	markerOptions = { icon:letteredIcon };
	
	var marker = new GMarker(point, markerOptions);
	var html = '<h5>' + name + '</h5>' + address + '<br />Tel: ' + telephone;
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function createSidebarEntry(marker, letter, name, address, telephone, distance, short_name) {
	var div = document.createElement('div');
	var html = '<h5><span class="letter">' + letter + '.</span> <a href="/home/our-brewers/'+ short_name + '" target="_top">' + name + '</a></h5>' + 
				'<div class="address">' + address + '</div>' + 
			 	'<div class="telephone">Tel: ' + telephone + '</div>' + 
				'<div class="clearance">&nbsp;</div>';
	
	// var html = '<h5><a href="/home/bars/bar/'+ short_name + '" target="_top">' + name + '</a></h5>' + address + '<div class="telephone">Tel: ' + telephone + '</div><div class="clearance">&nbsp;</div>';
	div.innerHTML = html;
	div.className = 'bar-entry';
	GEvent.addDomListener(div, 'click', function() {
		window.top.location = '/home/our-brewers/' + short_name;
	});
	GEvent.addDomListener(div, 'mouseover', function() {
		div.className = 'bar-entry-over';
	});
	GEvent.addDomListener(div, 'mouseout', function() {
		div.className = 'bar-entry';
	});
	return div;
}