var map;
var geocoder;


window.addEvent('domready', function()
{
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById("map"));
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());

		map.setCenter(new GLatLng(55.0, -5.0000), 5);
		//showAddress('389 Honeypot Lane, Stanmore, HA7 1JJ');
		add_page_elements();
	}

});


function add_page_elements()
{
	var show_all_link = new Element('button', {
			'html': 'Show All Distributors',
			'events': {
				'click': show_all_distributors
		    }
	});
	
	var search_button = new Element('button', {
			'html' : 'Check &raquo;',
			'events' : {
				'click': get_nearest_stores
			}
	});
	
	search_button.inject($('map'),'before');
	
	show_all_link.inject($('map'),'before');
}

function show_all_distributors()
{
	map.clearOverlays();

	var myRequest = new Request({method: 'get',
								url: 'http://www.artlinedecor.com/stores.php',
								onComplete: showdistributors})
						.send('dist=all_locations');
}

function get_nearest_stores()
{
	map.clearOverlays();

	var address = document.getElementById("addressinp").value;
	geocoder.setBaseCountryCode('uk');
	geocoder.getLatLng(
    	address,
    	function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.setCenter(point, 9);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address);
				var myRequest = new Request({method: 'get',
											 url: 'http://www.artlinedecor.com/stores.php',
											 onComplete: showdistributors})
									.send('dist=nearest&lat='+point.lat()+'&lng='+point.lng());
			}
		}
	);
}

function showdistributors(responseText, responseXML)
{
	var locations	= responseXML.getElementsByTagName('location');

	for (var i = 0; i < locations.length ; i++)
	{
		var lat	  = locations[i].getElementsByTagName('lat')[0].firstChild.data ;
		var long  = locations[i].getElementsByTagName('long')[0].firstChild.data ;	
		var name  = locations[i].getElementsByTagName('name')[0].firstChild.data ;	
		var address  = locations[i].getElementsByTagName('address')[0].firstChild.data ;	
		var telephone  = locations[i].getElementsByTagName('tel')[0];
		
		if (telephone.firstChild) telephone = telephone.firstChild.data;
		else telephone = '-';

		plotpoint(lat,long,name,address,telephone);
	}

}


function plotpoint(latitude,longitude,name,address,telephone)
{
	var point = new GLatLng(latitude,longitude);
	var marker = new GMarker(point);

	GEvent.addListener(marker, 'click', function(){ 
		marker.openInfoWindowHtml(
			"<h2>"+name+"</h2><p>"+address+"</p><p>Tel: "+telephone+"</p>"
		);
	}); 
	
	map.addOverlay(marker);
}
