$(document).ready(function() {

  var $messagePopup = $('.popup');

  $messagePopup.dialog({
    autoOpen: false,
    modal: true,
    width: 725,
    height: 'auto',
    draggable: true,
    closeText: 'X',
    hide: 'clip',
    show: 'drop'
  });

  $('#SearchContent').each( function() {
    $('.map-button').click( function() {
      var address = $(this).closest('.elements').find('.address').val();
      var geocoder = new google.maps.Geocoder();

      if (geocoder) {
        geocoder.geocode({ 'address': address }, function (results, status) {
          console.log(results[0]);
          if (status == google.maps.GeocoderStatus.OK) {
            var lat = results[0].geometry.location.lat();
            var lng = results[0].geometry.location.lng();
            //$('#map').remove();
            //$('.popup').html('<div id="map"></div>');
            google_map_load(lat, lng);
          } else {
            $('#map').html('<p>No address found</p>');
          }
        });
      }

      $messagePopup.dialog('open');

      return false;
    });
  });

  // google map
  function google_map_load(lat, lng) {
    var myLatlng = new google.maps.LatLng(lat,lng);
    var mapCenter = new google.maps.LatLng(lat,lng);

    var myOptions = {
      zoom: 15,
      center: mapCenter,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map
    });

    infowindow.open(map,marker);
  }
});

