var geocoder;
var icon;
var map;
var gdir;
var gmarkers = [];
var i = 0;
var zipcode;
var radius;
var startingAddress;
var endAddress;

function findLocations(_zipcode, _radius)
{
	if(_zipcode.length < 1 && _radius.length < 1)
	{
	    if(document.getElementById('zipcode').value.length < 1)
	        zipcode = 66044;
	    else
    		zipcode = parseInt(document.getElementById('zipcode').value);
		radius = parseInt(document.getElementById('radius').options[document.getElementById('radius').selectedIndex].value);
	}
	else
	{
		zipcode = _zipcode;
		radius = _radius;
	}

    document.getElementById('locations').style.textAlign = 'center';
    document.getElementById('locations').innerHTML = '<img src="' + loading.src + '" width="24" height="24" alt="Loading" style="padding-top: 10px;"/>';

	var xml = '<Location zipcode="' + zipcode + '" radius="' + radius + '"/>';
	send_xml_response_xml_async('http://www.xpreswash.com/centralservice/publicwebsite/getlocationsinradius.xpw', xml, showLocations);
}

function showLocations(xmlHttp)
{
	//clearing overlay'd markers
	map.clearOverlays();

	//setting maps center point
	setCenterPoint(zipcode);

	//clearing sidebar addresses
	document.getElementById('locations').innerHTML = '';

	var response = xmlHttp.responseXML;

	var locations = response.getElementsByTagName('Location');
	if(locations.length < 1)
	{
	    var html = '<div id="noresults" class="smaller">';
	    html    += '<p>No locations were found around the zipcode ' + zipcode + ', please expand your search radius and try again.</p>';
	    html    += '<p>OR</p>';
	    html    += '<p><input type="button" value="Show All Locations" onclick="findLocations(66044, 2000);return false;"></p>';
	    html    += '</div>';
	    
	    document.getElementById('locations').style.textAlign = 'left';
		document.getElementById('locations').innerHTML = html;
	}
	else
	{
        document.getElementById('locations').style.textAlign = 'left';
	    document.getElementById('locations').innerHTML = '<p class="smaller">There are ' + locations.length + ' XpresWash Locations in Your Area</p>';
	
		for(var i=0;i<locations.length;i++)
		{
			var address = locations[i].getAttribute("address1").replace("#","");
			if(locations[i].getAttribute("address2").length > 0)
				address += " " + locations[i].getAttribute("address2");
			address += ", " + locations[i].getAttribute("city") + ", " + locations[i].getAttribute("state") + " " + locations[i].getAttribute("zipcode");
		
			var name = locations[i].getAttribute("desc");
			var description = locations[i].getAttribute("address1");
			if(locations[i].getAttribute("address2").length > 0)
				description += "<br/>" + locations[i].getAttribute("address2");
			description += "<br/>" + locations[i].getAttribute("city") + ", " + locations[i].getAttribute("state") + " " + locations[i].getAttribute("zipcode");
			if(radius != 2000)
    			description += "<br/>Distance: approximately " + locations[i].getAttribute("distance") + " miles";

			var lat = locations[i].getAttribute("lat");
			var lng = locations[i].getAttribute("long");
			
			showAddress(address, name, description, lat, lng);
		}
	}
}

function setCenterPoint(zipcode)
{
	//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	if(radius != 2000)
	{
		geocoder.getLatLng( zipcode, function(point)
		{
			if(!point)
				alert(zipcode + " not found");
			else
				map.setCenter(point, 6);
		});
	}
}

function showAddress(address, name, description, lat, lng)
{
	var waterDropIcon = new GIcon(G_DEFAULT_ICON);
	waterDropIcon.image = "http://www.xpreswash.com/dev/images/waterdrop.gif";
	waterDropIcon.shadow = "http://labs.google.com/ridefinder/images/mm_0_shadow.png";
	waterDropIcon.iconSize = new GSize(13, 19);
	waterDropIcon.shadowSize = new GSize(22, 20);
	waterDropIcon.iconAnchor = new GPoint(6, 20);

	point  = new GLatLng(lat, lng);
	var marker = new GMarker(point, {icon:waterDropIcon});

	GEvent.addListener(marker, "click", function()
	{
		var id;
		
		for(var i=0;i<gmarkers.length;i++)
		{
			if(gmarkers[i] == marker)
				id = i;
		}
		
		var locations = document.getElementById('locations').getElementsByTagName('div');
		
		for(var i=0;i<locations.length;i++)
		{
		    locations[i].style.backgroundColor = '#E0E0E0';
		}
		
		document.getElementById("div" + id).scrollIntoView(true);
        document.getElementById("div" + id).style.backgroundColor = '#d6ccc7';

		marker.openInfoWindowHtml("<b>" + name + "</b><br/>" + description + "<br/><a href=\"http://maps.google.com/maps?f=d?hl=en&saddr=&daddr=" + address + "&ie=UTF8\" target=\"_blank\">Get Directions</a>");
	});

	gmarkers[i] = marker;
	var html = '<div id="div' + i + '" class="smaller">';
	html    += '<p>';
	html    += '<a href="#" onclick="addressClick(' + i + ');return false;">' + name + '</a><br/>';
	html    += description + '<br/>';
	html    += '<a href="http://maps.google.com/maps?f=d?hl=en&saddr=&daddr=' + address + '&ie=UTF8" target="_blank" onclick="addressClick(' + i + ');return true;">Get Directions</a>';
	html    += '</p>';
	html    += '</div>';
	document.getElementById('locations').innerHTML += html;
	i++;
	
	map.addOverlay(marker);
}

function addressClick(i)
{
	GEvent.trigger(gmarkers[i], "click");
}

function loadmap()
{
	if (GBrowserIsCompatible()) 
	{
      	map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(45, -95), 3);
		map.setUIToDefault();
		
		geocoder = new GClientGeocoder();
		GEvent.addListener(gdir, "error", handleGDirErrors);
	}
}

function handleGDirErrors()
{
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else 
		alert("An unknown error occurred.");
}