// Set custom icons
var icon = new GIcon();
icon.image = "http://" + location.hostname + "/app/css/images/map_icon.png";
icon.shadow = "http://" + location.hostname + "/app/css/images/map_icon_shadow.png";
icon.iconSize = new GSize(33, 33);
icon.shadowSize = new GSize(33, 33);
icon.iconAnchor = new GPoint(3, 23);
icon.infoWindowAnchor = new GPoint(19, 1);

var clusterIcon = new GIcon();
clusterIcon.image = "http://" + location.hostname + "/app/css/images/map_cluster_icon.png";
clusterIcon.shadow = "http://" + location.hostname + "/app/css/images/map_cluster_icon_shadow.png";
clusterIcon.iconSize = new GSize(41, 41);
clusterIcon.shadowSize = new GSize(41, 41);
clusterIcon.iconAnchor = new GPoint(4, 32);
clusterIcon.infoWindowAnchor = new GPoint(25, 2);

var homeIcon = new GIcon();
homeIcon.image = "http://" + location.hostname + "/app/css/images/map_home_icon.png";
homeIcon.shadow = "http://" + location.hostname + "/app/css/images/map_home_icon_shadow.png";
homeIcon.iconSize = new GSize(24, 34);
homeIcon.shadowSize = new GSize(34, 34);
homeIcon.iconAnchor = new GPoint(2, 33);
homeIcon.infoWindowAnchor = new GPoint(23, 0);

// Global marker define
var highlightMarker;

// Request ID tracking
var requestID = 1000;

// Function to zoom in on a certain area
function clusterZoom(minLat, maxLat, minLon, maxLon) {

	// Create new latlngbounds object from bounds
	var clusterBounds = new GLatLngBounds(new GLatLng(minLat, minLon), new GLatLng(maxLat, maxLon));
	// Create center point
	var clusterCenter = new GLatLng((maxLat + minLat) / 2, (maxLon + minLon) / 2);
	// Change the map
	spotMap.setCenter(clusterCenter, spotMap.getBoundsZoomLevel(clusterBounds));

}

// Showing spots on the map
function showSpots(properties) {

	// Show loading box if present
	if ($(".loadingstatus").length) $(".loadingstatus").show();

	// Init arguments
	if (typeof properties == "undefined") properties = {};
	if (typeof properties.mapFormat != "undefined") mapFormat = properties.mapFormat;
	else mapFormat = "both";
	addArgs = '';

	// Set additional arguments

	// Spot map id
	if (typeof properties.map != "undefined") spotMap = properties.map;

	// Spot ID specified
	if (typeof properties.spotID != "undefined") {
		addArgs = addArgs + "&spotid=" + properties.spotID;
	}

	// Only search within bounds of map
	if (typeof properties.withinBoundriesOnly == "undefined" || properties.withinBoundriesOnly == true) {
		currentBounds = spotMap.getBounds();
		southWestPoint = currentBounds.getSouthWest();
		northEastPoint = currentBounds.getNorthEast();
		centerPoint = spotMap.getCenter();
		addArgs = addArgs + "&north_lat=" + northEastPoint.lat() + "&south_lat=" + southWestPoint.lat() + "&west_lng=" + southWestPoint.lng() + "&east_lng=" + northEastPoint.lng() + "&zoom_level=" + spotMap.getZoom();
	}

	// Add tag
	if (typeof properties.tag != "undefined" && properties.tag != false) {
		addArgs = addArgs + "&tags=" + properties.tag;
	}

	// Get only certain author's spots
	if (typeof properties.authorID != "undefined" && properties.authorID != false) {
		addArgs = addArgs + "&author_id=" + properties.authorID;
	}

	// Look for search terms
	if (typeof properties.searchTerm != "undefined" && properties.searchTerm != false) {
		addArgs = addArgs + "&searchq=" + encodeURIComponent(properties.searchTerm);
	}

	// Look for extra sorting
	if (typeof properties.sortBy != "undefined" && properties.sortBy != false) {
		addArgs = addArgs + "&sort_by=" + properties.sortBy;
	}

	// Look for limits
	if (typeof properties.limit != "undefined" && properties.limit != false) {
		addArgs = addArgs + "&amount=" + properties.limit;
	}

	// Look for year
	if (typeof properties.year != "undefined" && properties.year != false) {
		addArgs = addArgs + "&year=" + properties.year;
	}

	// Look for current
	if (typeof properties.currentOn != "undefined" && properties.currentOn != false) {
		addArgs = addArgs + "&current=true";
	}

	// Clear previous overlays
	if (typeof properties.clearPrevious == "undefined" || properties.clearPrevious == true) spotMap.clearOverlays();

	// Update request ID so old requests get lost
	var thisRequestID = requestID = Math.floor(Math.random() * 10001);

	// Do AJAX request
	dataURL = "/api/eventsearch/?format=json" + addArgs;

	$.getJSON(dataURL, function(results){

		if (thisRequestID != requestID) return false;

		// Clear previous overlays again in case they persisted while loading
		if (typeof properties.clearPrevious == "undefined" || properties.clearPrevious == true) spotMap.clearOverlays();

		// Set an icon at the location the user is searching from
		if (typeof searchQuery != 'undefined' && !spotMap.getMarkerById(99999)) {
			var centerLocation = new GLatLng(startLat, startLon);
			var thisMarker = new PdMarker(centerLocation, homeIcon, 99999);
			spotMap.addOverlay(thisMarker);
		}

		// Show clusters
		if (results.clusters) {
	   		for (var i = 0; i < results.clusters.length; i++) {
	   			thisCluster = results.clusters[i];
	   			if (!spotMap.getMarkerById(thisCluster.id)) {
	   				var thisMarker = new PdMarker(new GLatLng(thisCluster.avglat,thisCluster.avglon), clusterIcon, thisCluster.id);

					if (mapFormat == "both" || mapFormat == "tooltip") {
						thisMarker.setTooltip(thisCluster.size + " Events");
					}
					if (mapFormat == "both" || mapFormat == "infowindow") {
						var windowTitle = "<a href=\"javascript:clusterZoom(" + thisCluster.minlat + ", " + thisCluster.maxlat + ", " + thisCluster.minlon + ", " + thisCluster.maxlon + ");\">" + thisCluster.size + " Event Cluster</a>";
						thisMarker.setDetailWinHTMLTitle(windowTitle);
						var windowHTML = '<a href="javascript:clusterZoom(' + thisCluster.minlat + ', ' + thisCluster.maxlat + ', ' + thisCluster.minlon + ', ' + thisCluster.maxlon + ');">Zoom in on this cluster</a><br/>Events in ' + thisCluster.cities + '<br/>';
						thisMarker.setDetailWinHTML(windowHTML);
						thisMarker.pendingWinClassName = "cluster";
					}

					spotMap.addOverlay(thisMarker);

				}
	   		}
	   	}

	   	// Show spots
	   	if (results.events) {
	   		for (var i = 0; i < results.events.length; i++) {
	   			thisSpot = results.events[i];

	   			if (!spotMap.getMarkerById(thisSpot.id)) {

	   				var thisMarker = new PdMarker(new GLatLng(thisSpot.lat,thisSpot.lon), icon, thisSpot.id);

					if (mapFormat == "both" || mapFormat == "tooltip") {
						thisMarker.setTooltip(thisSpot.name);
					}

					if (mapFormat == "both" || mapFormat == "infowindow") {

						// Set title
						var windowTitle = "<a href=\"" + thisSpot.url + "\">" + thisSpot.name + "<\/a>";
						thisMarker.setDetailWinHTMLTitle(windowTitle);

						// Get image
						var spotImage;
						if (thisSpot.image) spotImage = thisSpot.image;
						else spotImage = "/content/no-photo.png";

						// Detailed HTML
						var windowHTML = "<img src=\"" + spotImage + "\" /><h4>Location:</h4><address>" + thisSpot.addressname + "<br/>" + thisSpot.address + "<br/>" + thisSpot.city;
						if (thisSpot.region && thisSpot.region != "no") windowHTML = windowHTML + ", " + thisSpot.region;
						windowHTML = windowHTML + "<br/>" + thisSpot.country + "</address><p><a href=\"" + thisSpot.url + "\">View event &raquo;</a></p>";

						thisMarker.setDetailWinHTML(windowHTML);
					}

					spotMap.addOverlay(thisMarker);

				}
	   		}
	   	}

	   	// Hide loading screen
	   	$(".loadingstatus").hide();

	});

}

// Redo zoom control with class
function BareZoomControl() {
}

// subclass GControl
BareZoomControl.prototype = new GControl();
BareZoomControl.prototype.initialize = function(map) {

	// Container
	var container = document.createElement("div");
	container.className = "mapzoom";

	// Zoom in button
	var zoomInDiv = document.createElement("div");
	zoomInDiv.className = "in";
	container.appendChild(zoomInDiv);
	zoomInDiv.appendChild(document.createTextNode("Zoom In"));
	GEvent.addDomListener(zoomInDiv, "click", function() {
		map.zoomIn();
	});

	// Zoom out button
	var zoomOutDiv = document.createElement("div");
	zoomOutDiv.className = "out";
	container.appendChild(zoomOutDiv);
	zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
	GEvent.addDomListener(zoomOutDiv, "click", function() {
		map.zoomOut();
	});

	map.getContainer().appendChild(container);
	return container;
}

// Put it in the top
BareZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// Redo type control with class
function BareTypeControl() {
}

// subclass GControl
BareTypeControl.prototype = new GControl();
BareTypeControl.prototype.initialize = function(map) {

	// Container
	var container = document.createElement("div");
	$(container).addClass("maptype");

	// Map button
	var mapTypeDiv = document.createElement("div");
	mapTypeDiv.id = "typemap";
	if (map.getCurrentMapType() == G_NORMAL_MAP) $(mapTypeDiv).addClass("active");
	container.appendChild(mapTypeDiv);
	mapTypeDiv.appendChild(document.createTextNode("Map"));
	GEvent.addDomListener(mapTypeDiv, "click", function() {
		map.setMapType(G_NORMAL_MAP);
		$(this).siblings().removeClass("active");
		$(this).addClass("active");
	});

	// Sat button
	var satTypeDiv = document.createElement("div");
	satTypeDiv.id = "typesat";
	if (map.getCurrentMapType() == G_SATELLITE_MAP) $(satTypeDiv).addClass("active");
	container.appendChild(satTypeDiv);
	satTypeDiv.appendChild(document.createTextNode("Sat"));
	GEvent.addDomListener(satTypeDiv, "click", function() {
		map.setMapType(G_SATELLITE_MAP);
		$(this).siblings().removeClass("active");
		$(this).addClass("active");
	});

	// Hyb button
	var hybTypeDiv = document.createElement("div");
	hybTypeDiv.id = "typehyb";
	if (map.getCurrentMapType() == G_HYBRID_MAP) $(hybTypeDiv).addClass("active");
	container.appendChild(hybTypeDiv);
	hybTypeDiv.appendChild(document.createTextNode("Map"));
	GEvent.addDomListener(hybTypeDiv, "click", function() {
		map.setMapType(G_HYBRID_MAP);
		$(this).siblings().removeClass("active");
		$(this).addClass("active");
	});

	map.getContainer().appendChild(container);
	return container;
}

// Put it in the top
BareTypeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}
