/* ----- popup functionaliteit -------*/
// de hoofdfunctie
function load(lat, lng, title) {
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom : 15,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.HYBRID,
		streetViewControl : true
	};

	
	
	var map = new google.maps.Map(document.getElementById("map"), myOptions);

	var marker = new google.maps.Marker( {
		position : latlng,
		map : map,
		title : "jeugddienst"
	});

	// To add the marker to the map, call setMap();
	//marker.setMap(map);

	var infowindow = new google.maps.InfoWindow( {
		content : title
	});

	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map, marker);
	});

	infowindow.open(map, marker);
}


/* ----- maps functionaliteit ------- */


var markers_archive = [];
var markers_current = [];
var markers_future = [];
var map;
function init(divid) {
	$("#" + divid).height($(document).height() - 100); // set the height of the map
	
	// start the initialize of the google maps
	map = loadMap(divid, 12);
	var diensten = getDiensten();
	
	createMarkers(diensten);

	
	showMarkers();
}

function clearMarkers() {
	var markers = [];
	
	markers = $.merge(markers, markers_archive);
	markers = $.merge(markers, markers_future);		
	markers = $.merge(markers, markers_current);				
	
	//Start generating the map
	var mapmarker = [];
	var bounds = new google.maps.LatLngBounds();

	$.each(markers, function(i, data) {
		var curMarker = data.marker;
		curMarker.setMap(null);
	});
	
	// Center the map
	//map.fitBounds(bounds);
	
	// Add the marks
	//var markerCluster = new MarkerClusterer(map, mapmarker);
}

function showMarkers() {
	clearMarkers();
	
	var markerSet = [];
	if ($("#archived").is(':checked')) {
		markersSet = $.merge(markerSet, createMarkerSet(markers_archive));
	}
	if ($("#future").is(':checked')) {
		markerSet = $.merge(markerSet, createMarkerSet(markers_future));		
	}
	if ($("#current").is(':checked')) {
		markerSet = $.merge(markerSet, createMarkerSet(markers_current));				
	}
	
	// Center the map
	map.fitBounds(bounds);
	
	// Add the marks
	var markerCluster = new MarkerClusterer(map, markerSet);
}

var bounds;
function createMarkerSet(markers) {
	//Start generating the map
	var mapmarker = [];
	bounds = new google.maps.LatLngBounds();

	$.each(markers, function(i, data) {
		var curMarker = data.marker;
		var curInfoWindow = data.infowindow;
		
		google.maps.event.addListener(curMarker, 'click', function() {
			closeAllInfoWindows();
			curInfoWindow.open(map, curMarker);
			$(".ds_button").button();			
		});
		
		curMarker = detectCollision(mapmarker,curMarker, 1);
		
		mapmarker.push(curMarker);
		bounds.extend(curMarker.getPosition());
	});
	
	return mapmarker;	
}


/*
 * initialize the google map
 */
function loadMap(elementId, zoom) {
	var latlng = new google.maps.LatLng(52.726082, 6.480588); // center position
	var myOptions = {
		zoom : zoom,
		center : latlng,
		mapTypeId : google.maps.MapTypeId.HYBRID,
		streetViewControl : true
	};
	return new google.maps.Map(document.getElementById(elementId), myOptions);
}

function createMarkers(diensten) {
	$.each(diensten, function(i,dienst){
		var content = $.View('ejs/diensten/dienst_info_window.ejs', {dienst: dienst});
		
		//which picture do we want to use
		var currentTime = new Date();
		var oldTime = (currentTime.getTime() / 1000) -(24 * 60 * 60); // een dienst is oud wanneer die 24 uur voor de huidige tijd ligt
		var futTime = (currentTime.getTime() / 1000) + (24 * 60 * 60); // een dienst is toekomst wanneer deze 24 uur na de huidige tijd ligt
		
		var image = "grn-pushpin.png";
		var display = false;
		if (dienst.datum < oldTime) {
			// oud
			image = "red-pushpin.png";
		} else if (dienst.datum > futTime) {
			//toekomst
			image = "ltblu-pushpin.png";
		} else {
		}

		var marker = createMarker(dienst.locatie.lat, dienst.locatie.lng, dienst.thema, image);
		var infowindow = new google.maps.InfoWindow({content: content});

		if (marker != null) {
			if (dienst.datum < oldTime) {			
				markers_archive.push({marker: marker, infowindow: infowindow});
			} else if (dienst.datum > futTime) {
				markers_future.push({marker: marker, infowindow: infowindow});
			} else {
				markers_current.push({marker: marker, infowindow: infowindow});				
			} 
		}
		
	});	
}

function createMarker(lat, lng, title, image) {
	return new google.maps.Marker( {
		position : new google.maps.LatLng(lat, lng),
		title : title,
		icon : "templates/jeugddiensten/images/icons/" + image
		});
}

function detectCollision(markers, marker, col) {
	var colStep = 0.0001;
	var rowStep = 0.00005;
	var maxCol = 5;
	
	$.each(markers, function(i,item){
		if ( marker.getPosition().equals(item.getPosition()) ) {
			
			var lat = marker.getPosition().lat(); 
			var lng = marker.getPosition().lng();				
			if (col != 0 && col % maxCol == 0) {
				lat = lat - rowStep;
				lng = lng - ((maxCol-1) * colStep);
			} else {
				lng = lng + colStep;				
			}
			
			var latlng = new google.maps.LatLng(lat, lng);
			marker.setPosition(latlng);
			
			col++;
			
			marker = detectCollision(markers, marker, col);
			return;
		}
	});
		
	return marker;
}

function closeAllInfoWindows() {
	$.each(markers, function(i,data) { data.infowindow.close(); });
}


/* ---- Support mousewheel and some keys ----- */
//belangrijke hulpfunctie
function ge(idname) {
	var element = document.getElementById(idname);

	return element;
}

// ----- mousewheel
function zoom(oEvent, s) {
	if (s == -120) {
		map.zoomOut();
	}

	if (s == 120) {
		map.zoomIn();
	}
}

function mwh() {
	var d = ge('map');

	if (d) {
		try {
			if (document.body.addEventListener) {
				d.addEventListener('DOMMouseScroll', function(oEvent) {
					zoom(oEvent, oEvent.detail * -40);
				}, false);
			} else {
				d.onmousewheel = function() {
					zoom(event, event.wheelDelta);
					return false;
				}
			}
		} catch (ex) {
		}
	}
}



/* ----- Below are functions to retrieve data ----- */

function getDiensten() {
	
	// Gather all the ids
	var ids = [];
	$.ajax({type: 'POST', url: 'server.php', dataType: 'json', async: false,
		data: {option: "diensten", action: "getOverview"},
	    success: function(data) {
			$.each(data.result.diensten, function(i,item){
				ids.push(item);
			});		
		}
	});

	// Gather the data of each dienst
	var diensten = [];
	$.each(ids, function(i, item) {
		$.ajax({type: 'POST', url: 'server.php', dataType: 'json', async: false,
			data: {option: "diensten", action: "get", id: item},
			success: function(json) {
				diensten.push(json.result.dienst);
			}
		});
	});
	
	return diensten;
}


function getDienst(id) {
	var postdata = { option: 'diensten',
			 		 action: 'bekijken',
			 		 outputtype: 'flat',
			 		 id: id
					 };

	$.post("index.php", postdata, function(content){
		//alert(content);

		$('#dienst_detail_content').html(content);
		//$('#dienst_detail_frame').slideDown();
		var tabs = $('#dienst_tabs').tabs();
		tabs.tabs('select', 0); // be sure to always start on the first tab!
		$('#dienst_detail_frame').dialog({ modal: true, height: 'auto', width: 700 });


		}, "html");
}
