if(typeof window.jQuery != 'undefined') $(function() {

  var $google_maps = $('img.google_map');
  
  if($google_maps.length) {
    var infowindow = null;
    var map = null;

    function popupInfoWindow() {
      if(this.title != '') {
        infowindow.setContent('<div class="gmap_infowindow">' + this.title.replace(',', '<br />') + '</div>');
        infowindow.open(map, this);
      }
    }

    window.google_map_initialize = function() {
      var geocoder = new google.maps.Geocoder();
      infowindow = new google.maps.InfoWindow({ content: '' });

      $google_maps.each(function() {
      	var $this = $(this);
        var $addresses = unescape(new RegExp('[\\?&]markers=([^&#]*)').exec(this.src)[1]).split('|');
        var $style = 'width:' + $this.width() + 'px;height:' + $this.height() + 'px;';
        var $mapdiv = $this.wrap('<div class="google_map" style="' + $style + '"></div>').parent();
        var bounds = new google.maps.LatLngBounds();

        map = new google.maps.Map($mapdiv.get(0), { 
          zoom: 14, 
          mapTypeId: google.maps.MapTypeId.ROADMAP, 
          center: new google.maps.LatLng(-34.397, 150.644) 
        });

        $.each($addresses, function() {
          var $address = unescape(this);

          geocoder.geocode({ 'address' : $address }, function(results, status) {
            if(status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;

              google.maps.event.addListener(new google.maps.Marker({
                map: map, 
                position: location, 
                title : $address
              }), 'click', popupInfoWindow);

              bounds.extend(location);
              map.setCenter(location);
            }
          });
        });

		var listener = google.maps.event.addListener(map, 'idle', function() { 
	        map.setZoom(map.getBoundsZoomLevel(bounds));
	        map.setCenter(bounds.getCenter());
			google.maps.event.removeListener(listener); 
		});

      });
    }

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=google_map_initialize";
    document.body.appendChild(script);
  }

});

