Geolocator = {
  geocoder: null,
  map: null,
  markers: [],
  doDirections: false,
  googleLink: true,
  directions: null,

  init: function(divId) {
  if (!divId)
    divId = "map";

  div = document.getElementById(divId);
  this.map = new GMap2(div);
  this.map.setCenter(new GLatLng(37.0625, -95.67706), 3);
  this.map.setUIToDefault();
  if (this.doDirections) {	
    this.directions = new GDirections(this.map, document.getElementById('map_directions_sidebar'));
    GEvent.addListener(this.directions, "error", function() {
      var code = Geolocator.directions.getStatus().code;
      var reason="Code "+code;
      alert("Failed to obtain directions, "+reason);
    });
  }
  this.geocoder = new GClientGeocoder();
},
createMarker: function (point, letter, name, address, city, state, accuracy) {

  var baseIcon = new GIcon(G_DEFAULT_ICON);
  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);

  // Create a lettered icon for this point using our icon class
  var letteredIcon = new GIcon(baseIcon);
  letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

  // Set up our GMarkerOptions object
  markerOptions = { icon:letteredIcon };
  var marker = new GMarker(point, markerOptions);

  var id = this.markers.length;
  var html = '<div class="geolocator-marker"><span class="geolocator-marker-name">';
  html += name + '</span><br/>' + address;
  html += "<br>" + city + ", " + state;
  if (this.doDirections) {
    html += '<div id="geolocator-marker-directions-click-' + id + '">Directions</a>';
    html +='<div class="geolocator-marker-directions" id="geolocator-marker-directions-' + id + '">Directions: ' +
    '<span class="to-here">To here</span>' +
    '<div class="address">From address:' +
    '<form id="geolocator_directions_form_' + id + '" action="javascript:Geolocator.getDirections(' + id + ')">' +
    '<input type="text" size="20" maxlength="40" name="saddr" class="saddr" value="" /><br>' +
    '<INPUT class="submit" value="Get Directions" TYPE="SUBMIT"><br>' +
    '<input type="hidden" name="daddr" value="' + point.lat() + ',' + 
    point.lng() + '"/></div></div>'; 
  } else if (this.googleLink) {
    var addressString = escape(address) + ',' + escape(city) + ',' + escape(state);

    html += '<div class="geolocator-marker-google-link">' +
      '<a target="_blank" href="http://maps.google.com/maps?f=q&hl=en&q=' +
      addressString + '&ie=UTF8&hnear=' + addressString + 
      '&iwloc=A&hq=' + escape(name) + '" ' +
      'onclick="pageTracker._trackEvent(\"Store Locator Clicks\", \"More Info Click\", \"' + name + ': ' + address + ', '  + city + ', ' + state + '\")' + 
      '>More info</a></div>';
  }
  if (accuracy != null && accuracy < 6) {
    html += '<div class="geolocator-low-accuracy">* Location may not be exact</div>';
  }
  GEvent.addListener(marker, 'click', function() {
    pageTracker._trackEvent("Store Locator Clicks", "Marker Click", name + ": " + address + ", "  + city + ", " + state);
    marker.openInfoWindowHtml(html);
  });
  GEvent.addListener(marker, 'infowindowopen', function() {
    $('#geolocator-marker-directions-click-' + id).click(function() {
      var windowObj = $('#geolocator-marker-directions-' + id);
      windowObj.addClass('geolocator-marker-show-directions');
      var win = Geolocator.map.getInfoWindow();
      var size = new GSize(windowObj.getInnerWidth(), windowObj.getInnerHeight());
      win.reset(null, null, size);
    });	  
  });
  GEvent.addListener(marker, 'infowindowclose', function() {
    $('geolocator-marker-directions-' + id).removeClass('geolocator-marker-show-directions');
  });
  this.markers.push(marker);
  return marker;
},

createSidebarEntry: function(marker, letter, name, address, city, state, distance) {
  var div = document.createElement('div');
  var html = '<div class="geolocator-sidebar">';
  html += '<div class="geolocator-sidebar-name">' + letter + '. ' + name + ' - more info &raquo;</div>';
  html += '<div class="geolocator-sidebar-address">' + address + '<br/>' + city + ', ' + state + '</div>';
  html += '<div class="geolocator-sidebar-distance"> (' + distance.toFixed(1) + ') miles</div>';
  html += '</div>';
  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;
},

codeAddress: function() {
  this.markers = [];
  if (this.doDirections) {
    document.getElementById('map_directions_sidebar').innerHTML = '';
  }
  var address = document.getElementById('address').value;
  if (this.geocoder) {
    this.geocoder.getLatLng(address, function(latlng) {
      if (!latlng) {
        alert('address not found!');
      } else {
        var latitude = latlng.lat();
        var longitude = latlng.lng();
        var radiusElement = document.getElementById('radius');
        var radius = radiusElement.options[radiusElement.selectedIndex].value;
        var attributesElement = document.getElementById("attributes");
        var attributes = attributesElement.options[attributesElement.selectedIndex].value;
        var searchUrl = "/markers?radius=" + escape(radius) + "&latitude=" + 
        escape(latitude) + "&longitude=" + escape(longitude);
        if (attributes != "") {
          searchUrl += "&attribute=product" + "&attributes=" + escape(attributes);
        }
        GDownloadUrl(searchUrl, function(data) {
          var map = Geolocator.map;
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName('marker');
          map.clearOverlays();

          var sidebar = document.getElementById('map_sidebar');
          sidebar.innerHTML = '';
          if (markers.length == 0) {
            sidebar.innerHTML = 'No results found.';
            map.setCenter(new GLatLng(37.0625, -95.67706), 3);
            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 city = markers[i].getAttribute('city');
            var state = markers[i].getAttribute('state');
            var distance = parseFloat(markers[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                parseFloat(markers[i].getAttribute('lng')));
            var accuracy = markers[i].getAttribute('accuracy');
            var letter = String.fromCharCode("A".charCodeAt(0) + i);

            var marker = Geolocator.createMarker(point, letter, name, address, city, state, accuracy);
            var sidebarEntry = Geolocator.createSidebarEntry(marker, letter, name, 
                address, city, state, distance);
            sidebar.appendChild(sidebarEntry);
            map.addOverlay(marker);
            bounds.extend(point);
          }
          $('.geolocator-marker-directions-click').each(function (e) {
            $('geolocator-marker-directions-' + id).addClass('geolocator-marker-show-directions');
          });


          $(function(){
            jQuery('.scroll-pane').jScrollPane({scrollbarWidth:16});
          });

          // Set max zoom level.  If it's too zoomed in, the map just
          // looks blank with a marker on it.
          var zoomLevel = map.getBoundsZoomLevel(bounds);
          if (zoomLevel > 13) {
            zoomLevel = 13;
          }        	    	        	    		  
          map.setCenter(bounds.getCenter(), zoomLevel);
        });
      }
    });						
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
},
getDirections: function(formId) {
  var markerForm = document.getElementById('geolocator_directions_form_' + formId);
  document.getElementById('map_sidebar').innerHTML = '';
  this.map.clearOverlays();
  sourceAddress = markerForm.saddr.value;
  destinationAddress = markerForm.daddr.value;
  this.directions.load('from: ' + sourceAddress + ' to: ' + destinationAddress);
}

};


