var map;
var geocoder;
var address;

$(document).ready(function(){
  $('form').submit(function(){
    if(notExists('#results')) {
	  $('body').prepend('<div id="results"></div>');
      $('#results').ajaxStart(function(){
        var spin = '<img src="images/elements/progress-spinner.gif" width="220" height="19" alt="Loading&#8230;" id="spinner" />';
        if($(this).html() == '') {
          $(this).html(spin);
        } else {
          if(notExists('#spinner')) { $(this).prepend(spin); }
        }
      });
	}
	$(this).attr('id') == 'find-ave' ? $('#find-street')[0].reset() : $('#find-ave')[0].reset();
	var d = $(this).serialize();
	d += '&ajax=true';
    $.ajax({
      url: $(this).attr('action'),
      cache: false,
	  type: "POST",
      data: d,
	  dataType: 'html',
      success: function(html){
        $("#results").html(html).bgiframe();
		if(notExists('#success')) { return; } else {
          $('#results').width($(document).width()).height($(document).height()).addClass('dimmer').click(function() {
		    $(this).remove();
		  });
		  $("#success").append('<div id="map"></div><a href="" id="close"><img src="images/elements/close.gif" width="16" height="16" alt="Close" /></a>').click(function(event){ event.stopPropagation(); });
		  $('#close').click(function() {
		    $('#results').remove();
			return false;
		  });
          address = $('#the-address').text() + ' new york city, ny';
		  loadmap(address);
		  GUnload();	
        }
      }
    });
    return false;
  });
  function loadmap(address) {
    map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    geocoder = new GClientGeocoder();
    geocoder.getLocations(address, addToMap);
  }
  function addToMap(response) {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
    place.Point.coordinates[0]);
    map.setCenter(point, 17);
    marker = new GMarker(point);
    map.addOverlay(marker);
	marker.openInfoWindowHtml(place.address);
  }
  $(window).unload( function () { GUnload(); } );
});

function notExists(id) { if($(id).length < 1) { return true; } }
