googlemap = {};
googlemap.activeMarker	= null;
googlemap.icon					= null;
googlemap.gmap					= null;
googlemap.geo						= null;
googlemap.markermanager	= null;
googlemap.markercluster	= null;
googlemap.markers				= new Array;
googlemap.mapTypes			= {mapTypes:[G_PHYSICAL_MAP,G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP ]};
googlemap.zoomLevel			= 9;
googlemap.latitude			= 52.119999;
googlemap.longitude			= 5.240479;
googlemap.bounds				= null;
googlemap.baloonsize		= 350;
googlemap.mapcontrol		=	1;
googlemap.maptype				= G_HYBRID_MAP;
googlemap.countrycode		= 'nl';

googlemap.latitude_id		= '';
googlemap.longitude_id	= '';
googlemap.address_id		='';


// ====== Array for decoding the failure codes ======
var gmapreasons=[];
gmapreasons[G_GEO_SUCCESS]            = "Success";
gmapreasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
gmapreasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
gmapreasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
gmapreasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
gmapreasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
gmapreasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
gmapreasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";




//unload googlemaps when we unload the document to prevent memory leakage :D
jQuery(window).unload( function () {
  GUnload();
});

googlemap.loadMap = function (div) {
	if (GBrowserIsCompatible()) {
    this.gmap = new GMap2(document.getElementById(div), this.mapTypes);
    this.gmap.setCenter(new GLatLng(this.latitude, this.longitude), this.zoomLevel);
    if(googlemap.mapcontrol==1){
      this.gmap.addControl(new GLargeMapControl3D());
    }else{
      this.gmap.addControl(new GSmallZoomControl3D());
    }
    this.gmap.addControl(new GMapTypeControl());
    
		if(googlemap.overviewcontrol==1){
			this.gmap.addControl(new GOverviewMapControl());
		}

    this.gmap.setMapType(googlemap.maptype);
    this.markermanager = new MarkerManager(this.gmap);
		
    this.bounds = new GLatLngBounds();
  }
}

googlemap.createMarker = function (id, name, lat, lng, html) {
  var point = new GLatLng(lat,lng);
  this.bounds.extend(point);
  var marker = new GMarker(point,{title:name, draggable:false});
  if(html) {
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html, {maxWidth:googlemap.baloonsize},{suppressMapPan:false});//}
		});
	}
  googlemap.markers.push(marker)
}

googlemap.loadGeoCoder = function () {
  googlemap.geo = new GClientGeocoder();
  googlemap.geo.setBaseCountryCode(googlemap.countrycode);

  var center = new GLatLng(googlemap.latitude,googlemap.longitude);
  
  googlemap.gmap.setCenter(center, 15);
  geocoder = new GClientGeocoder();
  var marker = new GMarker(center, {draggable: true});
  googlemap.gmap.addOverlay(marker);


  GEvent.addListener(marker, "dragend", function() {
    var point = marker.getPoint();
    googlemap.gmap.panTo(point);
    jQuery(googlemap.latitude_id).val(point.lat().toFixed(5));
    jQuery(googlemap.longitude_id).val(point.lng().toFixed(5));
  });

  GEvent.addListener(googlemap.gmap, "moveend", function() {
    googlemap.gmap.clearOverlays();
    var center = googlemap.gmap.getCenter();
    var marker = new GMarker(center, {draggable: true});
    googlemap.gmap.addOverlay(marker);
    jQuery(googlemap.latitude_id).val(center.lat().toFixed(5));
    jQuery(googlemap.longitude_id).val(center.lng().toFixed(5));
    GEvent.addListener(marker, "dragend", function() {
      var point = marker.getPoint();
      googlemap.gmap.panTo(point);
      jQuery(googlemap.latitude_id).val(point.lat().toFixed(5));
      jQuery(googlemap.longitude_id).val(point.lng().toFixed(5));
    });
  });
}

// ====== Geocoding ======
googlemap.getAddress = function (search) {
  googlemap.geo.getLocations(search, function (result){
    // If that was successful
    if (result.Status.code == G_GEO_SUCCESS) {
      // Lets assume that the first marker is the one we want
      jQuery(googlemap.address_id).val(result.Placemark[0].address);
      var p = result.Placemark[0].Point.coordinates;
      jQuery(googlemap.longitude_id).val(p[0]);
      jQuery(googlemap.latitude_id).val(p[1]);

      googlemap.gmap.clearOverlays();
      var center = new GLatLng(p[1],p[0]);
      googlemap.gmap.setCenter(center, 15);
      var marker = new GMarker(center, {draggable: true});
      googlemap.gmap.addOverlay(marker);

      GEvent.addListener(marker, "dragend", function() {
        var point = marker.getPoint();
        googlemap.gmap.panTo(point);
        jQuery(googlemap.longitude_id).val(point.lng().toFixed(5));
        jQuery(googlemap.latitude_id).val(point.lat().toFixed(5));
      });

      GEvent.addListener(googlemap.gmap, "moveend", function() {
        googlemap.gmap.clearOverlays();
        var center = googlemap.gmap.getCenter();
        var marker = new GMarker(center, {draggable: true});
        googlemap.gmap.addOverlay(marker);
        jQuery(googlemap.longitude_id).val(center.lng().toFixed(5));
        jQuery(googlemap.latitude_id).val(center.lat().toFixed(5));

        GEvent.addListener(marker, "dragend", function() {
          var point = marker.getPoint();
          googlemap.gmap.panTo(point);
          jQuery(googlemap.longitude_id).val(point.lng().toFixed(5));
          jQuery(googlemap.latitude_id).val(point.lat().toFixed(5));
        });
      });
    }
    // ====== Decode the error status ======
    else {
       // === if we were sending the requests to fast, try this one again and increase the delay
       var reason="Code "+result.Status.code;
       if (gmapreasons[result.Status.code]) {
         reason = gmapreasons[result.Status.code]
       }
       alert("Fout bij opzoeken: "+reason);
    }
  });
}

