﻿var map={};
var geocoder;
var initX = 0;
var initY = 0;
var zoomLevel = 8;
var Gevonden;


function InitMap(mapType) 
{



    //Initialiseren van de kaart
	if (GBrowserIsCompatible()) 
	{
		map=new GMap2(document.getElementById('map'), {logoPassive:true});
		geocoder = new GClientGeocoder();
		
		// SetMapView is created during the pageload
		if( typeof(SetMapView) != "undefined" ) 
		{
		    SetMapView(map);
		}
		else
		{
		
		    if (initX == 0 && initY == 0)
		    {
		        map.setCenter(new GLatLng(52.0998, 5.1196), 2, mapType);
		    }
		    else
		    {
		        //Centreer op meest recent bijgekomen object.
		        //initX,initY zijn al gezet bij OnLoad event pagina
		        map.setCenter(new GLatLng(initX, initY), zoomLevel, mapType);
		    }
		}
		 
        map.enableContinuousZoom();
        map.enableDoubleClickZoom();	
		map.enableScrollWheelZoom();
		var topRight = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(20,20));
		map.addControl(new GLargeMapControl(), topRight);
		
		map.mkrMgr=new ClusterManager(map);
		map.markers = [];
	}
	
}

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " is niet gevonden!");
        } else {
          map.setCenter(point, 13);
          var marker = new GMarker(point, { icon:getIcon('common/img/icons/Found.png')});
          
          if (Gevonden != null){
            map.removeOverlay(Gevonden);
          }
          
          Gevonden = marker;
          map.addOverlay(marker);
          //marker.openInfoWindowHtml(address);
        }
      }
    );
  }
}

function SetInitialMapCentre(x,y,zoom)
{
    initX = x;
    initY = y;
    zoomLevel = zoom;
}

function SetOneIcon()
{
	    //Tijdelijk een icon op de kaart
        var marker=new GMarker(new GLatLng(52.0998,-15.0), 
		    { icon:getIcon('common/img/icons/Hotspot.png')});
		    
		marker.id = '1';                                //ID
		marker.url = 'common/img/varaan_klein.jpg';    //URL thumbnail
		

		
	    marker.naam = 'Test icoon';                     //Naam object
		    
	    GEvent.addListener(marker, 'mouseover', function(){
	    
    	                map.mkrMgr.ShowToolTip(this);            
	                });
	    GEvent.addListener(marker, 'mouseout', function(){
	                   map.mkrMgr.HideToolTip();
	                });
	    GEvent.addListener(marker, 'click', function() {
                       map.mkrMgr.ShowObject(this, map);
                    });
		    
        map.addOverlay(marker);
}

function getIcon(url)
{
    //creer icon. URL variabel
    var icon = new GIcon();
    icon.image = url;
    icon.iconSize=new GSize(32, 32);
	icon.shadow='common/img/icons/ShadowDefault.png';
	icon.iconAnchor=new GPoint(16, 32);
	return icon;
}

function InitNGJMap() 
{
    //
    // wordt 1x aangeroepen vanuit Default.aspx
    //
    document.onresize = MapResize();
    InitMap(G_PHYSICAL_MAP);
    //maak map met markers eerst leeg
    
    map.mkMgr = new ClusterManager(map);    //zet de cluster manager er bij..
	map.markers = [];
	
	//menno bijgezet..
	GetAllNGJObjecten();
};

function CenterMapOnObject(dLat, dLon, dZoomlevel)
{

    //FUNCTIE OM IN TE ZOOMEN OP een object of plaats
    
    if(map.getZoom() > dZoomlevel){
    // DE KAART IS VERDER INGEZOOMED DAN dZoomlevel, behoud het huidige zoomlevel:
        map.setCenter(new GLatLng(dLat, dLon), map.getZoom(), map.getCurrentMapType());
    } else {
    // DE KAART MAG INGEZOOMED WORDEN:
        map.setCenter(new GLatLng(dLat, dLon), dZoomlevel, map.getCurrentMapType());
    }
    
    
};


function GetAllNGJObjecten()
{        
    //maak map met markers eerst leeg
	map.markers = [];
    NGJ.UI.Web.NGJMapWebService.GetNGJObjecten(GetNGJObjecten_CallBack);
}

function GetNGJObjecten_CallBack(result) 
{
   createMarkers(result);
}


function createMarkers(jsonMarkers) 
{
var marker;
var jsonMarker;

if(jsonMarkers != null) {
for (var i=0; i <jsonMarkers.length; i++)
    {
        jsonMarker = jsonMarkers[i];
        
        
        //Glog.write( " marker aan het maken...");
        icoon = jsonMarker.Icoon;
        var icoon_pad;
        
        switch(icoon){
        case "NAT GEO JUNIOR CLUB": icoon_pad = 'common/img/icons/NGJClub.png' ;
        break;
        case "Hot spot": icoon_pad = 'common/img/icons/Hotspot.png' ;
        break;
        case "Spreekbeurt": icoon_pad = 'common/img/icons/Spreekbeurt.png';
        break;
        default:
        case "Jouw vraag": icoon_pad = 'common/img/icons/Mix.png';
        
        }
        
        
        //marker=new GMarker(new GLatLng(jsonMarker.X,jsonMarker.Y), { icon:getIcon('common/img/icons/Hotspot.png')});
        marker=new GMarker(new GLatLng(jsonMarker.X,jsonMarker.Y), {title:jsonMarker.Titel, icon:getIcon(icoon_pad)});
        
        marker.id = jsonMarker.PK;
        marker.url = jsonMarker.Tooltip_afbeelding;
        marker.naam = jsonMarker.Titel; 
        
        GEvent.addListener(marker, 'mouseover', function(){
    	              map.mkrMgr.ShowToolTip(this);            
	                });
	    GEvent.addListener(marker, 'mouseout', function(){
	                  map.mkrMgr.HideToolTip();
	                });
	    GEvent.addListener(marker, 'click', function() {
                       map.mkrMgr.ShowObject(this, map);
                    });
        map.markers.push(marker);
    }
    map.mkrMgr.addMarkers(map.markers);
	map.mkrMgr.refresh();

}

}



function MapResize()
{
/*
   var mapDiv = document.getElementById('map');
   if( mapDiv ) mapDiv.style.height = (GetHeight()) + 'px';
   
   var input = document.getElementById('input');
   if( input ) input.style.top = (GetHeight() - 80) + 'px';
  */
}
	
/*
----------------------------------------------------------------------------------------------------------------
	ClusterManager Version 1.1.4
	A marker manager for the Google Maps API
	http://googlemapsapi.martinpearman.co.uk/ClusterManager
	Copyright Martin Pearman 2008.
	Last updated 26th January 2008
	This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
	You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

function ClusterManager($map, $options){
	this._map=$map;
	this._mapMarkers=[];
	this._mapMarkersIconBounds=[];
	this._ClusterManagers=[];
	this._ClusterManagersEventListeners=[];
	if (typeof($options)=='undefined'){
		$options={};
	}
	this.fitMapToMarkers=($options.fitMapToMarkers===false)?false:true;
	if ($options.fitMapMaxZoom){
		this.fitMapMaxZoom=$options.fitMapMaxZoom;
	}
	if ($options.markers){
		this.addMarkers($options.markers);
	}
	this.borderPadding=$options.borderPadding?$options.borderPadding:256;
	this.intersectPadding=$options.intersectPadding?$options.intersectPadding:0;
	this.clusteringEnabled=($options.clusteringEnabled===false)?false:true;
	if ($options.ClusterManagerIcon){
		this._ClusterManager.icon=$options.ClusterManagerIcon;
	} else {
		this._ClusterManager.icon=new GIcon();
		this._ClusterManager.icon.image='common/img/icons/IconGroep.png';
		//this._ClusterManager.icon.shadow='common/img/mapicons/ShadowDefault.png';
	    this._ClusterManager.icon.iconSize=new GSize(45, 39);
	    this._ClusterManager.icon.iconAnchor=new GPoint(22, 39);
	}
	this._cancelMoveEnd=false;
	GEvent.bind(this._map, 'moveend', this, this._moveEnd);
	GEvent.bind(this._map, 'zoomend', this, this._zoomEnd);
	GEvent.bind(this._map, 'maptypechanged', this, this.refresh);
}

ClusterManager.prototype.addMarkers=function($markers){
	for (var i=$markers.length-1; i>=0; i--){
		$markers[i]._isVisible=false;
	}
	/*
	if (this.fitMapToMarkers){
		var $markersBounds=new GLatLngBounds();
		for (i=$markers.length-1; i>=0; i--){
			$markersBounds.extend($markers[i].getLatLng());
		}
		var $fitMapToMarkersZoom=this._map.getBoundsZoomLevel($markersBounds);
		
		if (this.fitMapMaxZoom && $fitMapToMarkersZoom>this.fitMapMaxZoom){
			$fitMapToMarkersZoom=this.fitMapMaxZoom;
		}
		this._map.setCenter($markersBounds.getCenter(), $fitMapToMarkersZoom);
	}
	*/
	this._mapMarkers=$markers;
	this._mapMarkersIconBounds=[];
};

ClusterManager.prototype._ClusterManager=function($clusterGroupIndexes){
	var $clusterGroupBounds, i, $ClusterManager, $map;
	$clusterGroupBounds=new GLatLngBounds();
	for (i=$clusterGroupIndexes.length-1; i>=0; i--){
		$clusterGroupBounds.extend(this._mapMarkers[$clusterGroupIndexes[i]].getLatLng());
	}
	$ClusterManager=new GMarker($clusterGroupBounds.getCenter(), {icon:this._ClusterManager.icon, title:'Klik voor inzoomen zodat de '+$clusterGroupIndexes.length+' iconen zichtbaar worden.'});
	$map=this._map;	//	reqd for function closure
	this._ClusterManagersEventListeners.push(GEvent.addListener($ClusterManager, 'click', function(){
		$map.setCenter($clusterGroupBounds.getCenter(), $map.getBoundsZoomLevel($clusterGroupBounds));
	}));
	return $ClusterManager;
};

ClusterManager.prototype._filterContainedMapMarkers=function(){
	var $borderPadding, $mapZoomLevel, $mapProjection, $mapPointSw, $activeAreaPointSw, $activeAreaLatLngSw, $mapPointNe, $activeAreaPointNe, $activeAreaLatLngNe, $activeAreaBounds, i;
	$borderPadding=this.borderPadding;
	$mapZoomLevel=this._map.getZoom();
	$mapProjection=this._map.getCurrentMapType().getProjection();
	$activeAreaBounds=this._map.getBounds();
	
	$mapPointSw=$mapProjection.fromLatLngToPixel($activeAreaBounds.getSouthWest(), $mapZoomLevel);
	$activeAreaPointSw=new GPoint($mapPointSw.x-$borderPadding, $mapPointSw.y+$borderPadding);
	$activeAreaLatLngSw=$mapProjection.fromPixelToLatLng($activeAreaPointSw, $mapZoomLevel);
	
	$mapPointNe=$mapProjection.fromLatLngToPixel($activeAreaBounds.getNorthEast(), $mapZoomLevel);
	$activeAreaPointNe=new GPoint($mapPointNe.x+$borderPadding, $mapPointNe.y-$borderPadding);
	$activeAreaLatLngNe=$mapProjection.fromPixelToLatLng($activeAreaPointNe, $mapZoomLevel);
	
	$activeAreaBounds.extend($activeAreaLatLngSw);
	$activeAreaBounds.extend($activeAreaLatLngNe);
	
	for (i=this._mapMarkers.length-1; i>=0; i--){
		this._mapMarkers[i]._makeVisible=$activeAreaBounds.containsLatLng(this._mapMarkers[i].getLatLng())?true:false;
	}
};

ClusterManager.prototype._filterIntersectingMapMarkers=function(){
	var $clusterGroup, i, j, $mapZoomLevel=this._map.getZoom();
	if (typeof this._mapMarkersIconBounds[$mapZoomLevel]=='undefined'){
		this._mapMarkersIconBounds[$mapZoomLevel]=this._mapMarkersBoundsArray();
	}
	for (i=this._mapMarkers.length-1; i>0; i--)
	{
		if (this._mapMarkers[i]._makeVisible){
			$clusterGroup=[];
			for (j=i-1; j>=0; j--){
				if (this._mapMarkers[j]._makeVisible && this._mapMarkersIconBounds[$mapZoomLevel][i].intersects(this._mapMarkersIconBounds[$mapZoomLevel][j])){
					$clusterGroup.push(j);
				}
			}
			if ($clusterGroup.length!==0){
				$clusterGroup.push(i);
				for (j=$clusterGroup.length-1; j>=0; j--){
					this._mapMarkers[$clusterGroup[j]]._makeVisible=false;
				}
				this._ClusterManagers.push(this._ClusterManager($clusterGroup));
			}
		}
	}
};

ClusterManager.prototype._mapMarkersBoundsArray=function(){
	var $mapProjection, $mapZoomLevel, i, $marker, $iconSize, $iconWidth, $iconHeight, $markerPoint, $markerPointX, $markerPointY, $iconAnchorPointOffset, $iconAnchorPointOffsetX, $iconAnchorPointOffsetY, $iconBoundsPointSw, $iconBoundsPointNe, $iconBoundsLatLngSw, $iconBoundsLatLngNe, $iconBounds=[], $intersectPadding;
	$intersectPadding=this.intersectPadding;
	$mapProjection=this._map.getCurrentMapType().getProjection();
	$mapZoomLevel=this._map.getZoom();
	for (i=this._mapMarkers.length-1; i>=0; i--){
		$marker=this._mapMarkers[i];
		
		$iconSize=$marker.getIcon().iconSize;
		$iconWidth=$iconSize.width;
		$iconHeight=$iconSize.height;
		
		$markerPoint=$mapProjection.fromLatLngToPixel($marker.getLatLng(), $mapZoomLevel);
		$markerPointX=$markerPoint.x;
		$markerPointY=$markerPoint.y;
		
		$iconAnchorPointOffset=$marker.getIcon().iconAnchor;
		$iconAnchorPointOffsetX=$iconAnchorPointOffset.x;
		$iconAnchorPointOffsetY=$iconAnchorPointOffset.y;
		
		$iconBoundsPointSw=new GPoint($markerPointX-$iconAnchorPointOffsetX-$intersectPadding, $markerPointY-$iconAnchorPointOffsetY+$iconHeight+$intersectPadding);
		$iconBoundsPointNe=new GPoint($markerPointX-$iconAnchorPointOffsetX+$iconWidth+$intersectPadding, $markerPointY-$iconAnchorPointOffsetY-$intersectPadding);
		$iconBoundsLatLngSw=$mapProjection.fromPixelToLatLng($iconBoundsPointSw, $mapZoomLevel);
		$iconBoundsLatLngNe=$mapProjection.fromPixelToLatLng($iconBoundsPointNe, $mapZoomLevel);
		
		$iconBounds[i]=new GLatLngBounds($iconBoundsLatLngSw, $iconBoundsLatLngNe);
	}
	return $iconBounds;
};

ClusterManager.prototype._moveEnd=function(){
	if(!this._cancelMoveEnd){
		this.refresh();
	} else {
		this._cancelMoveEnd=false;
	}
};

ClusterManager.prototype.refresh=function(){
	var i,j;
	this._removeClusterManagers();
	this._filterContainedMapMarkers();
	if (this.clusteringEnabled && this._map.getZoom()<this._map.getCurrentMapType().getMaximumResolution()){
		this._filterIntersectingMapMarkers();
	}
	for (i=this._ClusterManagers.length-1; i>=0; i--){
		this._map.addOverlay(this._ClusterManagers[i]);
	}
	for (i=this._mapMarkers.length-1; i>=0; i--){
		j=this._mapMarkers[i];
		if (!j._isVisible && j._makeVisible){
			this._map.addOverlay(j);
			j._isVisible=true;
		}
		if (j._isVisible && !j._makeVisible){
			this._map.removeOverlay(j);
			j._isVisible=false;
		}
	}
};

ClusterManager.prototype._removeClusterManagers=function(){
	for (var i=this._ClusterManagers.length-1; i>=0; i--){
		this._map.removeOverlay(this._ClusterManagers[i]);
	}
	for (i=this._ClusterManagersEventListeners.length-1; i>=0; i--){
		GEvent.removeListener(this._ClusterManagersEventListeners[i]);
	}
	this._ClusterManagers=[];
	this._ClusterManagersEventListeners=[];
};

ClusterManager.prototype.removeMarkers=function(){
	for (var i=this._mapMarkers.length-1; i>=0; i--){
		if (this._mapMarkers[i]. _isVisible){
			this._map.removeOverlay(this._mapMarkers[i]);
		}
		delete this._mapMarkers[i]. _isVisible;
		delete this._mapMarkers[i]._makeVisible;
	}
	this._removeClusterManagers();
	this._mapMarkers=[];
	this._mapMarkersIconBounds=[];
};

ClusterManager.prototype._zoomEnd=function(){
	this._cancelMoveEnd=true;
	this.refresh();
};


// Shows popup with the contents of the passed marker
ClusterManager.prototype.ShowObject = function(marker, map, hideList) 
{
    // The code for this method is generated in UserControl: Map
    // parameter: ID of object 
   	ShowObjectDetails(marker.id);
};

ClusterManager.prototype.ShowToolTip = function(marker){

    var mX = globalMouseX;
    var mY = globalMouseY;

   document.getElementById("tooltip").style.display = 'block'; 
   marker.url = marker.url.replace("~/","");
    
    //document.getElementById("tooltip").innerHTML = "<table><tr><td><div style=\"width:145px; height:84px; overflow: hidden;\"><img style=\"display: block;\" src=\""+marker.url+"\"/></div></td><td>"+marker.naam+"<br/></td></tr></table>";
   
   if (marker.url != "Afbeeldingen/Icoon/_tn.jpg"){
   document.getElementById("tooltip").innerHTML = "<table><tr><td><div style=\"height:75px; overflow: hidden;\"><img style=\"display: block;\" src=\""+marker.url+"\"/></div></td><td>"+marker.naam+"<br/></td></tr></table>";
   }
  else
   {
   document.getElementById("tooltip").innerHTML = "<table><tr><td>"+marker.naam+"<br/></td></tr></table>";
   }

   // alert(mX);
   
/*
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=marker.getIcon().iconSize.height;
	var icon_y = -offset.y + point.y + anchor.y;
	var icon_x = offset.x - point.x - anchor.x;


var point= map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom()); 
var offset= map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom()); 
var anchor=marker.getIcon().iconAnchor; 	
var width=marker.getIcon().iconSize.width; 

	var icon_x = offset.x - point.x - anchor.x;
	
	alert(icon_x);
*/	
	
	/*
	
    if (icon_x < (map.getSize().width/2)){  //icoon zit op de linker helft van de kaart
        xpos = offset.x - point.x - anchor.x + width;
    }else{                                  //icoon zit op de rechter helft van de kaart
    xpos = offset.x - point.x - anchor.x - document.getElementById("tooltip").clientWidth;
    }
    
    if(icon_y < (map.getSize().height/2)){  //icoon zit op de onderste helft van de kaart
    ypos = -offset.y + point.y +anchor.y;
    }else{                                  //icoon zit op de onderste helft van de kaart
    ypos = -offset.y + point.y +anchor.y - 92;
    }
    

    document.getElementById("tooltip").style.bottom =  ypos+'px';
    document.getElementById("tooltip").style.left = xpos+'px';
    document.getElementById("tooltip").style.height = 'auto';
    */
};

ClusterManager.prototype.HideToolTip = function()
{

    document.getElementById("tooltip").innerHTML = "";
    document.getElementById("tooltip").style.display = 'none'; 
    
};


