//Declaring some variables we will be using
var gmap_search_state = false;

var map;
var markerArray = [];
var circleArray = [];
var totalCircleArray = [];
var polygons_on_map_array = [];
var xmlhttp;
var targetDiv = "infotop";
var selected = false;
var overNode;
var markerSelected = "";
var highlightCircle;
var currentMarker;
var toggleCircles = false;

// This function is called from index.php
function initialize_map() {
	// We will only do this function if the browser is compatible
	if (GBrowserIsCompatible()) {
		// Adding the google map into the div called #mapcanvas
		map = new GMap2(document.getElementById("mapcanvas"), {
			googleBarOptions : {
				style : "new"
			}
		});
		// Center the map on Leiden
		map.setCenter(new GLatLng(52.162687, 4.493294), 11); // Vars should
																// go to config
		map.setUIToDefault();

		/*
		 * Go through the array 'markers' (Declared in index.php) and add a
		 * marker for each marker stored in the array using our addMarker
		 * function. If the latLng of the marker is both 0
		 */
		for ( var i = 0; i < markers.length; i++) {
			var current = markers[i];
			if (current.latitude[0] > 0 || current.latitude[0] < 0) {
				addMarker(current, i);
			}
		}

		GEvent.addListener(map, "click", function() {
			if (!overNode == true)
				deSelect();
		});

		GEvent.addListener(map, "zoomend", function() {
			mapZoomed();
		});

		suggestMarkers("");

		new MarkerClusterer(map, markerArray);
	}
}

// This function will contain the displaying and not displaying of nodes on the
// map
function toggleMyKml() {

}

// This function adds a marker with an object from our 'marker'array defined in
// index.php
function addMarker(current, i) {
	var latitude = Number(current.latitude[0]);
	var longitude = Number(current.longitude[0]);

	var displayIcon;
	var currentstatus = current.status[0];
	if (currentstatus == "up") {
		displayIcon = greenIcon;
	} else {
		displayIcon = redIcon;
	}

	var marker = new GMarker(new GLatLng(current.latitude[0],
			current.longitude[0]), {
		title : current.name[0],
		icon : displayIcon
	});

	// Added mouseover listener that calls on our mouseOver function when the
	// mouse moves over a marker on the map
	GEvent.addListener(marker, 'mouseover', function() {
		mouseOverNode(current.id, current.name[0], latitude, longitude);
	});
	GEvent.addListener(marker, 'click', function() {
		mouseClickNode(current.id, current.name[0], marker);
	});
	GEvent.addListener(marker, 'mouseout', function() {
		mouseOutNode(current.id, current.name[0]);
	});

	markerArray.push(marker);
	// circleArray.push(circle);
	return marker;
}

// Our mouseover function for single nodes. Gives the ID(our own given ID) and
// the name of the node.
function mouseClickNode(id, name, marker) {
	if (selected == true) {
		deSelect();
		markerSelected = "";
	}

	if (markerSelected == marker) {
		deSelect();
		markerSelected = "";
	} else {
		selected = true;
		markerSelected = marker;
		for ( var i = 0; i < markers.length; i++) {
			var currentmarker = markers[i];
			if (currentmarker.name[0] == marker.getTitle()) {
				if (currentmarker.status[0] == "up") {
					marker.setImage("../img/sleutelGroenSelected.png");
				} else {
					marker.setImage("../img/sleutelRoodSelected.png");
				}

			}
		}
		loadXMLDoc("inc/node_info.php?type=single&name=" + name + "&a="
				+ Math.random());
	}
}
// Our mouseover function for single nodes. Gives the ID(our own given ID) and
// the name of the node.
function mouseOverNode(id, name, latitude, longitude) {
	overNode = true;
	if (!selected == true) {

		drawCircle(latitude, longitude, 0.1, "#6C3", 1, 0.75, "#0F0", .2, 200);
		polygons_on_map_array.push(polygon);
		map.addOverlay(polygon);

		loadXMLDoc("inc/node_info.php?type=single&name=" + name + "&a="
				+ Math.random());// Path should be in config

		/*
		 * Hieronder verdergaan met dekking
		 */

	}
}

function mouseOutNode(id, name) {
	overNode = false;
	map.removeOverlay(polygon);

}

// Our mouseover function for Cluster nodes. 'markers' is an array containing
// all markers within the cluster
function mouseOverCluster(markers) {
	if (!selected == true) {
		// Make 'markers' array (containing gmarkers) into an array containing
		// only the titles(names) of the markers
		var markerTitles = new Array;
		var markerLatLngs = new Array;

		for ( var i = 0; i < markers.length; i++) {
			markerTitles.push(markers[i].marker.getTitle());
			markerLatLngs.push(markers[i].marker.getLatLng());
		}

		var markerTitleSerialized;

		// start
		var a_php = "";
		var total = 0;

		for ( var i = 0; i < markerTitles.length; i++) {
			++total;
			a_php = a_php + "s:" + String(i).length + ":\"" + String(i)
					+ "\";s:" + String(markerTitles[i]).length + ":\""
					+ String(markerTitles[i]) + "\";";
		}
		a_php = "a:" + total + ":{" + a_php + "}";
		// end

		loadXMLDoc("inc/node_info.php?type=cluster&markers=" + a_php + "&rand="
				+ Math.random());
		/*
		 * Hieronder verdergaan met dekking
		 */

		for ( var i = 0; i < markerLatLngs.length; i++) {
			latLng = String(markerLatLngs[i]);

			pos = latLng.indexOf(',');
			pos2 = latLng.length - 1;

			var latitude = Number(latLng.substring(1, pos));
			var longitude = Number(latLng.substring(2 + pos, pos2));

			drawCircle(latitude, longitude, 0.1, "#6C3", 1, 0.75, "#0F0", .2);

			map.addOverlay(polygon);
			polygons_on_map_array.push(polygon);
		}
	}
}

// Our click function for Cluster nodes. 'markers' is an array containing all
// markers within the cluster
function clickCluster(markers) {
	if (selected == true)
		deselect();

	// Let the rest of the program know that something is selected
	select();

	// Make 'markers' array (containing gmarkers) into an array containing only
	// the titles(names) of the markers
	var markerTitles = new Array;
	for ( var i = 0; i < markers.length; i++) {
		markerTitles.push(markers[i].marker.getTitle());

	}

	var markerTitleSerialized;

	// start
	var a_php = "";
	var total = 0;

	for ( var i = 0; i < markerTitles.length; i++) {
		++total;
		a_php = a_php + "s:" + String(i).length + ":\"" + String(i) + "\";s:"
				+ String(markerTitles[i]).length + ":\""
				+ String(markerTitles[i]) + "\";";
	}
	a_php = "a:" + total + ":{" + a_php + "}";
	// end

	loadXMLDoc("inc/node_info.php?type=cluster&markers=" + a_php
			+ "&sel=selected" + "&a=" + Math.random())
}

function mouseOutCluster(markers) {
	removeAllPolgygons();
}

function mapZoomed() {

	if (!markerSelected == "") {
		markerSelected.setImage("../img/sleutelGroenSelected.png");
	}

	if (highlightCircle) {
		map.removeOverlay(highlightCircle);
	}
}

function removeAllPolgygons() {
	for ( var i = 0; i < polygons_on_map_array.length; i++) {
		var currentpolygon = polygons_on_map_array[i];
		map.removeOverlay(currentpolygon);

	}
	polygons_on_map_array.clear();
}

function select() {
	selected = true;
}

function deSelect() {
	map.removeOverlay(highlightCircle);
	selected = false;
	loadXMLDoc("inc/node_info.php");
	if (!markerSelected == "") {
		for ( var i = 0; i < markers.length; i++) {
			var currentmarker = markers[i];
			if (currentmarker.name[0] == markerSelected.getTitle()) {
				if (currentmarker.status[0] == "up") {
					markerSelected.setImage("../img/sleutelGroen.png");
				} else {
					markerSelected.setImage("../img/sleutelRood.png");
				}

			}
		}
		markerSelected = "";
	}

	removeAllPolgygons();

}

function removeOtherSelect() {
	for ( var i = 0; i < markerArray.length; i++) {
		currentmarker = markerArray[i];
		currentmarker.setImage("../sleutelGroen.png");
	}
	return true;
}

// Code from w3schools. http://www.w3schools.com/dom/dom_http.asp
function loadXMLDoc(url, targetDiv) {
	xmlhttp = null;
	if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp != null) {
		xmlhttp.onreadystatechange = state_Change();
		xmlhttp.open("GET", url, true);
		xmlhttp.send(null);
	} else {
		alert("Your browser does not support XMLHTTP.");
	}
}

function state_Change() {
	if (xmlhttp.readyState == 4) {// 4 = "loaded"
		if (xmlhttp.status == 200) {// 200 = "OK"
			document.getElementById(targetDiv).innerHTML = xmlhttp.responseText;
		} else {
			alert("Problem retrieving data:" + xmlhttp.statusText);
		}
	}
}

function loadSuggest(url) {
	xmlhttp = null;
	if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp != null) {
		xmlhttp.onreadystatechange = state_ChangeSuggest;
		xmlhttp.open("GET", url, true);
		xmlhttp.send(null);
	} else {
		alert("Your browser does not support XMLHTTP.");
	}
}

function state_ChangeSuggest() {
	if (xmlhttp.readyState == 4) {// 4 = "loaded"
		if (xmlhttp.status == 200) {// 200 = "OK"
			document.getElementById("searchlist").innerHTML = xmlhttp.responseText;
		} else {
			alert("Problem retrieving data:" + xmlhttp.statusText);
		}
	}
}

function suggestMarkers(value) {
	loadSuggest("inc/suggestions.php?value=" + value + "&a=" + Math.random());
}

function goToMarker(value) {
	for ( var i = 0; i < markerArray.length; i++) {
		var name = markerArray[i].getTitle();

		if (name == value) {
			map.setCenter(markerArray[i].getLatLng(), 15);
			loadXMLDoc("inc/node_info.php?type=single&name=" + value + "&a="
					+ Math.random())
		}
	}
}

function toggleGoogleSearchMap() {
	if (gmap_search_state) {
		gmap_search_state = false;
	} else {
		gmap_search_state = true;
	}

	if (gmap_search_state) {
		map.enableGoogleBar();
	}

	if (!gmap_search_state) {
		map.disableGoogleBar();
	}
}

function toggleAllCircles() {
	toggleCircles = !toggleCircles;

	if (toggleCircles == true) {
		for ( var i = 0; i < markers.length; i++) {
			var current = markers[i];
			if (current.latitude[0] > 0 || current.latitude[0] < 0) {
				drawCircle(Number(current.latitude[0]), Number(current.longitude[0]), 0.1, "#6C3", 1, 0.75, "#0F0", .2);

				map.addOverlay(polygon);
				totalCircleArray.push(polygon);
			}
		}
	} else {
		for ( var i = 0; i < totalCircleArray.length; i++) {
			var currentpolygon = totalCircleArray[i];
			map.removeOverlay(currentpolygon);

		}
		totalCircleArray.clear();
	}
}
