var map;
var gdir;
var geocoder = null;
var addressMarker;	

function initialize_google_maps() {
  if (GBrowserIsCompatible()) {      
    map = new GMap2($('map'));
    map.addControl(new GLargeMapControl());
	  map.addControl(new GMapTypeControl());
	  map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(40.6, -73.4), 10);
	  
    gdir = new GDirections(map, $('directions'));	
    GEvent.addListener(gdir, 'error', handle_errors);   
    
    geocoder = new GClientGeocoder();            
  }
}

function set_destination(store,  destination) {
  $('destination').value = decodeURIComponent(destination);
  $('destination-text').setHTML('Destination: <strong>'+decodeURIComponent(store)+'</strong> ' + decodeURIComponent(destination));
  $('directions').empty();
  $('get-stores').setStyle('display', 'none');
  $('get-directions').setStyle('display', 'block');
}
    
function get_directions() {
  origin  = $('origin').value;
  destination = $('destination').value;
  
  if(destination) gdir.load("from: " + origin + " to: " + $('destination').value);
  else alert('Please select a store location.');
}

function handle_errors(){
  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);  
}

function load_destination(store, address) {
  address = decodeURIComponent(address);
  if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            var marker = new GMarker(point);
            map.addOverlay(marker);
            GEvent.addListener(marker, "click", function() {
              set_destination(store, address);
            });
          }
        );
  }
}

function set_center(address) {
  address = decodeURIComponent(address);
  geocoder.getLatLng(
    address,
    function(point) {
      map.setCenter(point, 10);
    }
  );
}

function show_results() {
  $('get-stores').setStyle('display', 'block');
  $('get-directions').setStyle('display', 'none');
}

window.addEvent('domready', function() {
  initialize_google_maps();
});