$(document).ready(function(){
  var geocoder;
  var map;
 
  var windowOffsetX = 26;
  var windowOffsetY = -54;
  
  var imageWidth = 200;
  var imageHeight = 150;
  
  var flickrKey = "08b9abd0c8bfeb0d4ea347c43473bcbf";
  var userID = "65453770@N00";
  var wait = 500;
  var pointCount = 0;

  initialize();

  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(52.507588,6.093661);
    var myOptions = {
      zoom: 15,
      center: latlng,
	  //disableDefaultUI: true,
	  scrollwheel:false,
	  navigationControl: true,
	  mapTypeControl: true,
	  mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,position: google.maps.ControlPosition.BOTTOM},
	  navigationControl: true,    
	  navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN,position: google.maps.ControlPosition.BOTTOM_LEFT},
	  //scaleControl: true,
	  //scaleControlOptions: {position: google.maps.ControlPosition.TOP_LEFT},
	  mapTypeId: google.maps.MapTypeId.ROADMAP  //ROADMAP, SATELLITE, HYBRID, TERRAIN	
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    placeBoerdamOffice("Van Nagellstraat 4, Zwolle, 8011 EB, Nederland", "BoerdamMarker", 0);
    getRandomPoint();
    //getFlickrData();
  }
 
  function inverseOrder(marker,b) {
      return -GOverlay.getZIndex(marker.getPoint().lat());
  }

  function laadAdres(address, image, divId, klantnaam, klantId) {
  var size = new google.maps.Size(14, 14);
  var thumb = new google.maps.MarkerImage("/img/markerKlanten.png", size);
	
	// Timeout omdat google maar 10 queries per zoveel seconden toelaat.
	setTimeout(function() {
		var googleApi = "ABQIAAAAp0Xoy41QCM-kRv0y0LOx1BTi5vciSCUuBgyjCHPrsW0SSEi_nRQhRMDcLdmUaMiicZYUwl4m0OjAWg";
		$.getJSON("http://maps.google.com/maps/geo?q=" + address + "&output=json&sensor=false&key=" + googleApi + "&callback=?", function(data){
		if(data.Status.code == 200) {
			var positieMarker = new google.maps.LatLng(data.Placemark[0].Point.coordinates[1], data.Placemark[0].Point.coordinates[0]);
			var marker = new google.maps.Marker({
			  map: map, 
			  position: positieMarker,
			  icon: thumb,
		      zIndexProcess:inverseOrder
		    });
		    var infowindowInhoud = "Boerdam zet ook " + klantnaam + " op de kaart.<br><a style='color: #00AEFF; font-weight: bold;' href='/klanten/" + klantId + "/" + klantnaam + "'>Bekijk klant</a>";
		    google.maps.event.addListener(marker, 'click', function() {
			var markerPos = positieMarker;
			overlay = new USGSOverlay(markerPos, map, infowindowInhoud, divId);
		    });
		} else {
			//alert("Error: " + data.Status.code + " - " + address + " | " + pointCount + " | " + wait );	
		}
       });  	  
	}, wait);
	
	pointCount = pointCount + 1;
	//if(pointCount > 5) {
		wait = wait + 500;
		//pointCount = 0;
	//}
  }
  
  function placeBoerdamOffice(address, image, divId) {
	  var size = new google.maps.Size(209, 37);
	  var thumb = new google.maps.MarkerImage("/img/markerBoerdamOffice.png", size, new google.maps.Point(0,0), new google.maps.Point(0, 0));
	 if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var marker = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location,
	          icon: thumb,
		      zIndexProcess:inverseOrder, 
		      cursor: "default"
          });

        } else {
          //alert("Geocode was not successful for the following reason: " + status + " : " + address );
        }
      });
    }  
  }
  
  function laadCoords(address, imagebig, image, divId, titel) {
  //image = (image) ? image : "/images/marker.png";
  var size = new google.maps.Size(75, 48);
  var thumb = new google.maps.MarkerImage(image, size);
  var marker = new google.maps.Marker({
            map: map, 
            position: address,
	      	icon: thumb,
	      	zIndexProcess:inverseOrder  
          });
		  var overlay;
		  var newWindow = true;
		  var infowindowInhoud = "<img src='" + imagebig + "' width='" + imageWidth + "' height='" + imageHeight + "' class='imageStyle'/>"
		  + "<strong>"+titel+"</strong>"
		  + ""; // hier komt de titel en tekst in
		  //alert(infowindowInhoud);
	    google.maps.event.addListener(marker, 'click', function() {
			var markerPos = address;
			overlay = new USGSOverlay(markerPos, map, infowindowInhoud, divId);
  	    });
  }
  
  // CMS data 
  function getRandomPoint() {
	$.getJSON("/includes/ajax_klantenmaps.asp",
		function(data){
			$.each(data.coordinaten,
			//Handelingen per foto
			function(i, item){
				if(item.adres != "") {
					var adresString = item.adres + ", " + item.postcode + ", " + item.woonplaats + ", " + item.land;
					var unieke_div = "popupMaps_"+item.id;
					laadAdres(adresString, "", unieke_div, item.klantnaam, item.id);
				}
			});
		});
    }
    
    function getFlickrData() { // http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=08b9abd0c8bfeb0d4ea347c43473bcbf&user_id=65453770@N00&format=json&jsoncallback=?
    	$.getJSON("http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=" + flickrKey + "&user_id=" + userID + "&format=json&jsoncallback=?",
		function(data){
			if(data.stat != "fail"){
				$.each(data.photos.photo,
				function(i, item){
					var farm = item.farm;
					var serverID = item.server;
					var fotoID = item.id;
					var secret = item.secret;
					//s	small square 75x75
					//t	thumbnail, 100 on longest side
					//m	small, 240 on longest side
					//-	medium, 500 on longest side
					//b	large, 1024 on longest side (only exists for very large original images)
					//o	original image, either a jpg, gif or png, depending on source format
					//Ik gebruik hier t omdat deze dan ook gelijk voor de div/infowindow kunnen gebruiken
					var type = "m";
					var image = "http://farm"
					+ farm
					+ ".static.flickr.com/"
					+ serverID
					+ "/"
					+ fotoID
					+ "_"
					+ secret
					+ "_"
					+ type
					+ ".jpg"

					var type = "s";
					var thumb = "http://farm"
					+ farm
					+ ".static.flickr.com/"
					+ serverID
					+ "/"
					+ fotoID
					+ "_"
					+ secret
					+ "_"
					+ type
					+ ".jpg"

					$.getJSON("http://api.flickr.com/services/rest/?"
					+ "&method=flickr.photos.geo.getLocation"
					+ "&api_key=" + flickrKey
					+ "&photo_id="
					+ item.id
					+ "&format=json"
					+ "&jsoncallback=?",
					function(data2){
						if(data2.stat != "fail"){
								var foto = data2.photo;
								var coordinaten = new google.maps.LatLng(foto.location.latitude, foto.location.longitude);
								var unieke_div = "popupMaps_"+foto.id;
								var titel = item.title;
								laadCoords(coordinaten, image, thumb, unieke_div, titel);
						}
					});
				});
			}
		});
    }
	  
  /* Rick */
function USGSOverlay(markerPos, map, infowindowInhoud, divId) {
  this.realPos = markerPos;
  this.map_ = map;
  this.div_ = null;
  this.divId_ = divId;
  this.inhoud_ = infowindowInhoud;

  // Explicitly call setMap() on this overlay
  this.setMap(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();
USGSOverlay.prototype.onAdd = function() {

  var div = document.createElement('DIV');
  div.style.position = "absolute";

  // Create an IMG element and attach it to the DIV.
  //var img = document.createElement("img");
  //img.src = this.image_;
  //img.style.width = "100%";
  //img.style.height = "100%";
  //div.appendChild(img);

  // Set the overlay's div_ property to this DIV
  this.div_ = div;

  // We add an overlay to a map via one of the map's panes.
  // We'll add this overlay to the overlayImage pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

USGSOverlay.prototype.draw = function() {
	
	//alert($("#"+this.divId_).attr("id"));
	
	if($("#"+this.divId_).attr("id") == undefined) {
        // Hide all
	  $(".mapsPopup").each(function() {
		$(this).css("visibility", "hidden");
	  });	
	
	  var overlayProjection = this.getProjection();
	
	  var divPos = overlayProjection.fromLatLngToDivPixel(this.realPos)
	  var markerX = divPos.x;
	  var markerY = divPos.y;
	
	  // Resize the image's DIV to fit the indicated dimensions.
	  var div = this.div_;
	  div.style.left = markerX + 15 + 'px';
	  div.style.top = (markerY-18) + 0 + 'px';
	  $(div).css({
		width: "202px",
		backgroundColor: "#000",
		color: "#fff",
		opacity: "0.95",
		lineHeight: "14px",
		padding: "8px",
	 	zIndex: "999999999",
		visibility: "visible"
			 });
	  //div.style.width = 100 + 'px';
	 // $(div).css(infowindowStyle);
	 // $(div).append(this.inhoud_);
	  $(div).addClass("mapsPopup");
	  $(div).attr("id",this.divId_ );
	  $(div).append(this.inhoud_);
	  //$(".imageStyle").css(imageStyle);
	} else {
		// Hide all
		$(".mapsPopup").each(function() {
			$(this).css("visibility", "hidden");
		});
		
		var overlayProjection = this.getProjection();
	
		var divPos = overlayProjection.fromLatLngToDivPixel(this.realPos)
		var markerX = divPos.x;
		var markerY = divPos.y;
		
		var div = $("#"+this.divId_);
		$("#"+this.divId_).css("visibility", "visible"); 
		$("#"+this.divId_).css("left", markerX + 15 + 'px'); 
		$("#"+this.divId_).css("top", (markerY-18) + 0 + 'px');
	}
}

USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}

USGSOverlay.prototype.hide = function() {
  /*if (this.div_) {
    this.div_.style.visibility = "hidden";
  }*/
}

USGSOverlay.prototype.show = function() {
 /* if (this.div_) {
    this.div_.style.visibility = "visible";
  }*/
}

USGSOverlay.prototype.toggle = function() {
  /*if (this.div_) {
    if (this.div_.style.visibility == "hidden") {
      this.show();
    } else {
      this.hide();
    }
  }*/
}
/* end Rick */
	
   });