$(document).ready(function() {
 
var geodata = '';
var geocoder = new GClientGeocoder();
var map_status = 0;

if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
}

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " wurde nicht gefunden.");
      } else {
        initMap(point);
      }
    }
  );
}

function initMap(point) {
  var mapControl = new GLargeMapControl();
  map.addControl(mapControl);
  map.disableDragging();
  
  map.setCenter(point, 16, G_SATELLITE_MAP);
  var marker = new GMarker(point, {draggable: true});
  map.addOverlay(marker);
  
  GEvent.addListener(marker, "dragend", function(position) {
    $('#attributesById_6_58_value').attr('value', position.y + ',' + position.x);
  });
  
  if($('#attributesById_6_58_value').attr('value') == '') {
    $('#attributesById_6_58_value').attr('value', marker.oa.y + ',' + marker.oa.x);
  }  
}
  
  function startMap() {
  if (GBrowserIsCompatible()) {
    
    if($('#attributesById_6_58_value').attr('value') != '') {
      // console.log("GEODATEN VORHANDEN");
      var geodata = $('#attributesById_6_58_value').attr('value').split(",");
      geodata = new GLatLng(geodata[0], geodata[1]);
      initMap(geodata);
    } else {
      // console.log("ADRESSE SUCHEN");
      address = $('#hplz').attr('value') + ' ' + $('#hort').attr('value') + ', ' + $('#hstrasse').attr('value');
      showAddress(address);
    }
  }
  }
  
  $('.map-show').click(function () {
    if(map_status == 1) {
      $('#map').show('', startMap());
      map_status = 0;   
    } else {
      $('#map').slideDown();
    }
    
  });
  
  $('.map-hide').click(function () {
    $('#map').slideUp();
  });
  
  if($('.map-show').attr('checked') == true) {
    startMap();
    map_status = 0;
  } else {
    map_status = 1;
    $('#map').hide();
  }

  
});
