var map = false;
var geocoder;
var marker = false;

jQuery(document).ready(function(){
		if ( typeof($('#map_canvas')[0]) != "undefined" ) {
        initializeMap("false");
        refreshMarker_call();
        
        $('#ortzw').bind('keyup change',function () {
		      refreshMarker_call();
		    });
		    $('#plz').bind('keyup change',function () {
		      refreshMarker_call();
		    });
		    $('#land').bind('change',function () {
		      refreshMarker_call();
		    });
    }
});

function refreshMarker_call() {
	refreshMarker($('#ortzw').val()+' '+$('#plz').val()+' '+$('#land').val());
}

//http://code.google.com/intl/de-DE/apis/maps/documentation/javascript/examples/index.html
function initializeMap(type) {
    var x = 13;
    var y = 48;
    var zoom1 = (type=="detail") ? 16 : 6;
    var myOptions = {
      zoom: zoom1,
      center: new google.maps.LatLng(y, x),
      mapTypeId: (type != "detail") ? google.maps.MapTypeId.ROADMAP : google.maps.MapTypeId.SATELLITE
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();
}
function refreshMarker( _geo ) {
    geocoder.geocode({"address":_geo}, 
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
		          	if ( !marker ) {
		          		marker = new google.maps.Marker({
							        position: results[0].geometry.location, 
							        map: map
							    });
		          	}
		          	else {
		          			marker.setPosition(results[0].geometry.location);
		                map.setCenter(results[0].geometry.location);
		          	}
                jQuery('#coordX').val(results[0].geometry.location.lat());
                jQuery('#coordY').val(results[0].geometry.location.lng());
                
			          //alert(results[0].formatted_address);
          }
          else {
                jQuery('#coordY').val('0');
                jQuery('#coordX').val('0');
                //alert("Geocode was not successful for the following reason: " + status);
          }
    });
}

