var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
    var gdir;
    var addressMarker;

if (document.getElementById('locationAddress').value != '') {
    showAddress(document.getElementById('locationAddress').value);
}

function showAddress(address){
    geocoder.getLatLng(address, function(point){
        if (!point) {
            alert('"' + address + '" not found!');
        }
        else {
            map.setCenter(point, 13);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            var locationName = document.getElementById('locationName').value;
            if (locationName != '') {
                marker.openInfoWindowHtml(locationName);
            }
            document.getElementById('locationLat').value = point.lat();
            document.getElementById('locationLng').value = point.lng();
        }
    });
}

function load(){
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(40, -100), 4);
    }
}

function searchLocations(){
    var address = document.getElementById('addressInput').value;
    geocoder.getLatLng(address, function(latlng){
        if (!latlng) {
            alert(address + ' not found');
        }
        else {
            searchLocationsNear(latlng);
        }
    });
}

function searchLocationsNear(center){
    var radius = document.getElementById('radiusSelect').value;
    var searchUrl = '/index.pl?arg0=Locate Store&arg1=search results&lat=' + center.lat() + '&lng=' + center.lng() + '&rad=' + radius;
    GDownloadUrl(searchUrl, function(data){
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('marker');
        map.clearOverlays();
        
        var sidebar = document.getElementById('sidebar');
        sidebar.innerHTML = '';
        if (markers.length == 0) {
            sidebar.innerHTML = 'No results found.';
            map.setCenter(new GLatLng(40, -100), 4);
            return;
        }
        
        var bounds = new GLatLngBounds();
        for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute('name');
            var address = markers[i].getAttribute('address');
            var phone = markers[i].getAttribute('phone');
            var distance = parseFloat(markers[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
            
            var marker = createMarker(point, name, phone, address);
            map.addOverlay(marker);
            var sidebarEntry = createSidebarEntry(marker, name, phone, address, distance);
            sidebar.appendChild(sidebarEntry);
            bounds.extend(point);
        }
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    });
}

function createMarker(point, name, phone, address){
    var marker = new GMarker(point);
		var from = document.getElementById('addressInput').value;
    var html = '<b>' + name + '</b> <br/>' + '<b>' + phone + '</b> <br/>' + address + '<br />' + '<a target="_blank" href="http://maps.google.com/maps?saddr='+from+'&daddr='+address+'">Get Directions</a>';
    GEvent.addListener(marker, 'click', function(){
        marker.openInfoWindowHtml(html);
    });
    return marker;
}

function createSidebarEntry(marker, name, phone, address, distance){
    var div = document.createElement('div');
    var html = '<b>' + name + '</b><br/>'+ '<b>' + phone + '</b> (' + distance.toFixed(1) + ' miles) <br/>' + address;
    div.innerHTML = html;
    div.style.cursor = 'pointer';
    div.style.marginBottom = '5px';
    GEvent.addDomListener(div, 'click', function(){
        GEvent.trigger(marker, 'click');
    });
    GEvent.addDomListener(div, 'mouseover', function(){
        div.style.backgroundColor = '#eee';
    });
    GEvent.addDomListener(div, 'mouseout', function(){
        div.style.backgroundColor = '#fff';
    });
    return div;
}

function showDirections(to) {
	
	
			var from = document.getElementById('addressInput').value;
			window.location='http://maps.google.com/maps?saddr='+from+'&daddr='+to;
	 if (GBrowserIsCompatible()=='asdf') {      
				alert(from+' : '+to);
	 
        map = new GMap2(document.getElementById("map"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

				//setDirections("San Francisco", "Mountain View", "en_US");
        setDirections(from, to, "en_US");
      }
    }

 

    
    function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    function handleErrors(){
	   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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
