﻿// GMap instance
var currentMap;

// In GeoSearch, move events should not refresh the markers
var inGeoSearch;

// The GEventListener instance that listens to map clicks for circle and poly search
var mapClickListener;

// A function that is called after the markers have been downloaded and all overlays cleared, but before new markers have been added, used to add cuurently active geozoeken markers
var addingNewMarkers;

// Options of the circle search markers
var radiusCenterOptions = null;
var radiusResizeOptions = null;
var radiusSearchOptions = null;

// poly search markers
var polyMarkers = [];

// poly search shaded area
var poly;

// poly search button
var polySearchButton = null;

// the current radius search
var currentRadiusSearch = null;

// the current poly search
var currentPolySearch = null;

// Get all the markers on the currently visible map
function getDefaultMarkers(clearOldFilter){

	// Don't get new markers if the view change is caused by the cluster code
	if (inClusterMarkerCreating)
		return;

	// Don't get new markers if the user is using the GeoSearch functions
	if(inGeoSearch){
		return;
	}

	if (!clearOldFilter)
		type = 'default'
	else {
		addingNewMarkers = null;
		type = 'wis';
	}
	
	getMarkers({
		type : type
	});
}

// Vraag de gebruiker om het middelpunt van de cirkel te bepalen om met cirkel zoeken te beginnen
function cirkelZoeken(){
	inGeoSearch = true;
	removeClickListener();
	showMapTip('Klik op de kaart om het middelpunt van de cirkel te bepalen, de straal wordt automatisch ingesteld en kan vervolgens worden aangepast.')	
	
	currentMap.clearOverlays();
	
	var handler = function(overlay, point){
		createCircle(point, getStraal(), currentMap, true);
		hideMapTip();
		removeClickListener();
	}
	
	// Voeg een klik handler toe die een cirkel maakt
	mapClickListener = GEvent.addListener(currentMap, 'click', handler);
}

// Vraag de gebruiker om 3 of 4 punten aan te geven waarbinnen gezocht met worden
function polyZoeken(){
	inGeoSearch = true;
	polyMarkers = [];
	removeClickListener();
	showMapTip('Klik op de kaart om 3 of 4 punten toe te voegen waarbinnen gezocht moet worden.')	
	
	currentMap.clearOverlays();
	
	var handler = function(overlay, point){
		leftClick(overlay, point);
		hideMapTip();
	}
	
	// Voeg een klik handler toe die een cirkel maakt
	mapClickListener = GEvent.addListener(currentMap, 'click', handler);
}

// Remove the map click listener		
function removeClickListener(){
		if(mapClickListener){
			GEvent.removeListener(mapClickListener);
			mapClickListener = null;
		}
}

// Stop met geo zoeken en toon alle campings op de kaart
function allesZoeken(){
	inGeoSearch = false;
	$('.plaatsTextBox').val('');
	removeClickListener();
	getDefaultMarkers(true);
}

// Toon wat toelichting aan de gebruiker
function showMapTip(text) {
	$('.MapTipPanel').css("display", "block");
	$('.MapTip').css("height", "0px");
	$('.MapTip').css("padding-top", "0px");
	$('.MapTip').css("padding-bottom", "0px");
	$('.MapTip').animate({ height: "30px", paddingTop: "10px", paddingBottom: "10px" }, 500)
	$('.MapTip').text(text)
}

// Ga cirkel zoeken obv lat lng in json param straal
function tekstZoekenCallBack(data, status){
	if ((!data) && (status == -1)) return; // Timeout occurred
	eval('var latlng = ' + data + ';');
	if(latlng){
		inGeoSearch = true;
		createCircle(new GLatLng(latlng.lat, latlng.lng), getStraal(), currentMap, true);
	} else {
		showMapTip("De plaats kan niet worden gevonden binnen uw huidige selectie. Pas uw selectie aan of probeer een andere plaatsnaam.");
	}
}

// Bepaal straal ahv de text input
function getStraal(){
	var res = parseInt($('#straalInput').val(), 10);
	if (res){
		if (res <= 99)
			return res;
		else {
			$('#straalInput').val('99');
			return 99;
		}
	}
	$('#straalInput').val('20');
	return 20;
}

// Verberg de toelichting
function hideMapTip(){
	$('.MapTipPanel').css('display', 'none')
}

function plaatsZoeken(){
	var $plaatsContainer = $('.plaatsParagraph');
	$plaatsContainer.css("visibility", "visible");
	$('.plaatsTextBox').focus();
	showMapTip("Vul een plaatsnaam in en druk op enter of klik op het vergrootglas.");
}

// Calculate boundary to contains all the markers around given center.
//  find anti-symmetry again mapCenter of lat and lng
function bestFitWithCenter(map, bounds, mapCenter) {
  var swLL = bounds.getSouthWest();
  var neLL = bounds.getNorthEast();
       
  //leave margin each side  
  var marginRatio = 0.0001;

  var minLat = Math.min(2*mapCenter.lat() - neLL.lat(), swLL.lat());                 
  var maxLat = Math.max(2*mapCenter.lat() - swLL.lat(),  neLL.lat());         
  var minLng = Math.min(2*mapCenter.lng() - neLL.lng(), swLL.lng());                
  var maxLng = Math.max(2*mapCenter.lng() - swLL.lng(), neLL.lng());
   
  //GLog.write("minLat="+minLat + ", minLng="+minLng);
  //GLog.write("maxLat="+maxLat + ", maxLng="+maxLng);
    
  var minLatLng = new GLatLng(minLat-marginRatio, minLng-marginRatio);
  var maxLatLng = new GLatLng(maxLat+marginRatio, maxLng+marginRatio);
  
  bounds.extend(maxLatLng);
  bounds.extend(minLatLng);      
  
  map.setZoom(map.getBoundsZoomLevel(bounds));
  map.setCenter(mapCenter);     
}

// Zoom out to display all the markers and set the map to the center
function bestFitBounds(map, bounds) {
	map.setCenter(bounds.getCenter());
	var zoomLevel = map.getBoundsZoomLevel(bounds)
	// Don't zoom out to all europe, then show the campings 1 zoom level higher
	if(zoomLevel == 3)
		zoomLevel++;
	map.setZoom(zoomLevel);
}

// Zoom out to display the given min/max latitude and longitude and set the map to the center
function bestFitMinMax(map, minLatitude, minLongitude, maxLatitude, maxLongitude) {
	var bounds = new GLatLngBounds(new GLatLng(minLatitude, minLongitude), new GLatLng(maxLatitude, maxLongitude));
	
	bestFitBounds(map, bounds);
}

var bubble;
var approot;
var gmap;
var currentCluster;

// If true, the cluster markers are in the process of being created, so the moveEnd event must not be triggered
var inClusterMarkerCreating;

function openCampingBubble(marker)
{
	var sterren = '';
	for (var i=0; i<marker.camping.sterren; i++)
		sterren += '*';

	var image	= '';
	if (marker.camping.imageurl && (marker.camping.imageurl != ''))
		image = '<img style="float:left; width:120px; height:91px; margin-right:10px;" src="' + approot + marker.camping.imageurl + '" alt="' + marker.camping.imagealt + '" />';
	else
		image = '<img style="float:left; width:100px; height:75px; margin-right:10px;" src="' + approot + 'images/noggeenfoto.gif" alt="Er zijn nog geen foto\'s voor deze camping." />';
		
	var internet = '';
	if (marker.camping.internetLandingPage && (marker.camping.internetLandingPage != ''))
		internet = '<span class="red">&gt;</span>&nbsp;<a href="http://' + marker.camping.internetLandingPage + '" onclick="StatistiekenWebService.RegisterClick(' + marker.camping.id + ', 9); return true;" target="_blank">' + marker.camping.internet + '</a>';

	var info = '<div style="padding-top:3px; padding-right:20px;float:left;width:250px;">' + 
								marker.camping.land + ' - ' + marker.camping.gebied + ' - ' + marker.camping.plaats + '<br />' +
								marker.camping.staanplaatsen + ' staanplaatsen<br />' +
								internet +
	           '</div>';

	var html = '<div style="left:16px;width:360px;top:12px;" class="campingInfoBoxName">' + marker.camping.naam + ' ' + sterren + '</div>' +
						 '<div style="position:absolute;left:13px;top:40px;">' + image + info + '</div>' +
						 '<div style="position:absolute;right:17px; top:14px; width:13px; height:13px; cursor:pointer;" onclick="if(bubble)bubble.hide();"></div>' +
						 '<a href="' + marker.camping.campingurl + '" onclick="StatistiekenWebService.RegisterClick(' + marker.camping.id + ', 1); return true;"><img src="images/meerinfo.gif" style="position:absolute; right:17px; bottom:22px; cursor:pointer;" alt="Klik voor meer info over deze camping" /></a>';

	if (bubble)
	    bubble.hide();
	bubble = new EBubble(gmap, approot + "images/campingpopup.png", new GSize(419, 157), new GSize(419, 157), new GPoint(0, 0), new GPoint(196, 150), true);
	bubble.openOnMarker(marker, html);
}

function openClusterMarkers(clusterMarker, clusteredMarkers) {

    if (clusteredMarkers.length > 3)
    {
        gmap.setCenter(clusterMarker.getLatLng(), gmap.getBoundsZoomLevel(clusterMarker.clusterGroupBounds));
	    return;
    }

    var info = '';
    
    for (var i = 0; i < clusteredMarkers.length; i++) {
        var camping = clusteredMarkers[i].camping;

        var image = '';
        if (camping.imageurl && (camping.imageurl != ''))
            image = '<img style="width:100px; height:75px; margin-right:10px;" src="' + approot + camping.imageurl + '" alt="' + camping.imagealt + '" />';
        else
            image = '<img style="width:100px; height:75px; margin-right:10px;" src="' + approot + 'images/noggeenfoto.gif" alt="Er zijn nog geen foto\'s voor deze camping." />';

        var top = 'top:' + (37 + (i * 10)) + 'px;';

        info += '<div style="position:relative;width:400px;height:80px;' + top + '">' +
                    '<div style="left:123px;width:267px;" class="campingInfoBoxName">' + camping.naam + '</div>' +
                    '<div style="position:absolute;left:13px;">' + image +
                    '<div style="position:absolute;left:110px;top:12px;width:180px;">' +
					camping.land + ' - ' + camping.gebied + ' - ' + camping.plaats + '<br />' +
					camping.staanplaatsen + ' staanplaatsen<br />' +
					'<a href="' + camping.campingurl + '" onclick="StatistiekenWebService.RegisterClick(' + camping.id + ', 1); return true;"><img src="images/meerinfo.gif" style="position:absolute;left:170px;top:35px;cursor:pointer;" alt="Klik voor meer info over deze camping" /></a>' +
					'</div>' +
					'</div>' +
					'</div>';
    }

    var html = '<div style="font-weight:bold;color:#e00e00;position:absolute;left:16px;top:12px;">' + clusteredMarkers.length + ' campings gevonden</div>' +
                    info + '<div style="position:absolute;right:17px; top:14px; width:13px; height:13px; cursor:pointer;" onclick="if(bubble)bubble.hide();"></div>';
    if (bubble)
        bubble.hide();
    switch (clusteredMarkers.length) {
        case 2:
            bubble = new EBubble(gmap, approot + "images/campingpopup_2.png", new GSize(419, 230), new GSize(419, 230), new GPoint(0, 0), new GPoint(196, 223), true);
            break;
        case 3:
            bubble = new EBubble(gmap, approot + "images/campingpopup_3.png", new GSize(419, 330), new GSize(419, 330), new GPoint(0, 0), new GPoint(196, 323), true);
            break;
        default:
            bubble = new EBubble(gmap, approot + "images/campingpopup.png", new GSize(419, 157), new GSize(419, 157), new GPoint(0, 0), new GPoint(196, 150), true);
    }
    bubble.openOnMarker(clusterMarker, html);
}

var isSingleClick = false;
var timedOpenBubble = null;

function initNewMarkers(data, status) {
	$(".waitDiv").css("display", "none");

	if ((!data) && (status == -1)) return; // Timeout occurred

	eval('var campingsData = ' + data);
	
	approot = campingsData.approot;
	
	gmap = campingsData.gmap;
	var campings = campingsData.campings;
	
	gmap.clearOverlays();

	if (campings) {
		var markersArray = [];
		var icon = new GIcon();
		icon.image = approot + "images/marker.png";
		icon.iconSize = new GSize(10, 13);
		icon.iconAnchor = new GPoint(5, 13);
		icon.infoWindowAnchor = new GPoint(5, -2);

		for (var i = 0; i < campings.length; i++) {
			var camping = campings[i];
			var marker = new GMarker(new GLatLng(camping.lat, camping.lng), { title: camping.naam, icon: icon });
			marker.camping = camping;

			// The click and dblclick listeners use a timeout to allow the dblclick to zoom the map instead of showing the camping details, it's a hack but it's the best solution i could find
			GEvent.addListener(marker, "click", function() {
				isSingleClick = true;
				if (timedOpenBubble != null)
					clearTimeout(timedOpenBubble);
				var marker = this;
				timedOpenBubble = setTimeout(function() { if (isSingleClick) openCampingBubble(marker) }, 200);
			});

			GEvent.addListener(marker, "dblclick", function() {
				isSingleClick = false;
				var marker = this;
				zoomlevel = currentMap.getZoom();
				zoomlevel++;
				currentMap.setCenter(marker.getLatLng(), zoomlevel);
				currentMap.setZoom(zoomlevel);
			});

			gmap.addOverlay(marker);
			markersArray.push(marker);
		}

		if (campingsData.doCluster) {
			// Create the cluster markers
			inClusterMarkerCreating = true;
			currentCluster = new ClusterMarker(gmap, { markers: markersArray });
			// cluster.fitMapToMarkers();
			currentCluster.clusterMarkerClick = function(args) { openClusterMarkers(args.clusterMarker, args.clusteredMarkers) };
			currentCluster.refresh(true);
			inClusterMarkerCreating = false;
		}

		if (campingsData.count > campings.length) {
			showMapTip("Er vallen " + campingsData.count + " campings binnen de huidige selectie. Daarvan worden er " + campings.length + " getoond. Zoom in om de campings te zien.");
		} else {
			hideMapTip();
		}
		
	} else {
		showMapTip("Er vallen geen campings binnen de huidige selectie. U kunt uw filter minder specifiek maken.");
	}

	showCount(campingsData.count);

	if (addingNewMarkers)
		addingNewMarkers();
}

// Refresh the cluster (triggered when the zoom or scroll has changed during geozoeken)
function refreshCluster() {
	if (currentCluster) {
		currentCluster.refresh(true);
	}
}

/*********************************************************************************/

/*
* LabeledMarker Class
*
* Copyright 2007 Mike Purvis (http://uwmike.com)
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class extends the Maps API's standard GMarker class with the ability
* to support markers with textual labels. Please see articles here:
*
*       http://googlemapsbook.com/2007/01/22/extending-gmarker/
*       http://googlemapsbook.com/2007/03/06/clickable-labeledmarker/
*/



// Constructor
function LabeledMarker(latlng, options){
    this.latlng = latlng;
    this.labelText = options.labelText || "";
    this.labelClass = options.labelClass || "markerLabel";
    this.labelOffset = options.labelOffset || new GSize(0, 0);
    
    this.clickable = options.clickable || true;
    
    if (options.draggable) {
    	// This version of LabeledMarker doesn't support dragging.
    	options.draggable = false;
    }
    
    GMarker.apply(this, arguments);
}

// It's a limitation of JavaScript inheritance that we can't conveniently
// extend GMarker without having to run its constructor. In order for the
// constructor to run, it requires some dummy GLatLng.
LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));


// Creates the text div that goes over the marker.
LabeledMarker.prototype.initialize = function(map) {
	// Do the GMarker constructor first.
	GMarker.prototype.initialize.apply(this, arguments);
	
	var div = document.createElement("div");
	div.className = this.labelClass;
	div.innerHTML = this.labelText;
	div.style.position = "absolute";
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);

	if (this.clickable) {
		// Pass through events fired on the text div to the marker.
		var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout'];
		for(var i = 0; i < eventPassthrus.length; i++) {
			var name = eventPassthrus[i];
			GEvent.addDomListener(div, name, newEventPassthru(this, name));
		}

		// Mouseover behaviour for the cursor.
		div.style.cursor = "pointer";
	}
	
	this.map = map;
	this.div = div;
}

function newEventPassthru(obj, event) {
	return function() { 
		GEvent.trigger(obj, event);
	};
}

// Redraw the rectangle based on the current projection and zoom level
LabeledMarker.prototype.redraw = function(force) {
	GMarker.prototype.redraw.apply(this, arguments);
	
	// We only need to do anything if the coordinate system has changed
	if (!force) return;
	
	// Calculate the DIV coordinates of two opposite corners of our bounds to
	// get the size and position of our rectangle
	var p = this.map.fromLatLngToDivPixel(this.latlng);
	var z = GOverlay.getZIndex(this.latlng.lat());
	
	// Now position our DIV based on the DIV coordinates of our bounds
	this.div.style.left = (p.x + this.labelOffset.width) + "px";
	this.div.style.top = (p.y + this.labelOffset.height) + "px";
	this.div.style.zIndex = z + 1; // in front of the marker
}

// Remove the main DIV from the map pane, destroy event handlers
LabeledMarker.prototype.remove = function() {
	GEvent.clearInstanceListeners(this.div);
	this.div.parentNode.removeChild(this.div);
	this.div = null;
	GMarker.prototype.remove.apply(this, arguments);
}


/*********************************************************************************/
