var markers = {};

function calcMarker(id) {
	var satInfo = PLib.QuickFind(id);
	return new GLatLng(satInfo.latitude, satInfo.longitude);
}

function createMarker(id, flash) {
	var position = calcMarker(id);
	var title = $("label[for='" + id + "']")[0].innerHTML;

	if ($("input#set_shownames")[0].checked) {
		var icon = new GIcon();
		icon.image = "";
		icon.iconAnchor = new GPoint(0, 0);
		if (flash) {
			icon.image = "server.py/label?mode=flash&id=" + id;
		}
		else {
			icon.image = "server.py/label?mode=normal&id=" + id;
		}
		markers[id] = new GMarker(position, { "title": title, "icon": icon });
		map.addOverlay(markers[id]);
		if (flash) {
			setTimeout("dimMarker('"+ id + "')", 3000);
		}
		createInfobox(id);
		GEvent.addListener(markers[id], "click", function() {
			selectedSatellite = id;
			map.openInfoWindow(markers[id].getLatLng(), popups[id]);
		});
		GEvent.addListener(markers[id], "mouseover", function() {
			highlightTrack(id);
			highlightFootprint(id);
		});
		GEvent.addListener(markers[id], "mouseout", function() {
			dimTrack(id);
			dimFootprint(id);
		});
	}
	else {
		$.get("server.py/icon?id=" + id, function(url) {
			if (url == "") {
				markers[id] = new GMarker(position, { "title": title });
			}
			else {
				var icon = new GIcon();
				icon.image = "";
				icon.iconAnchor = new GPoint(12, 12);
				icon.image = url;
				markers[id] = new GMarker(position, { "title": title, "icon": icon });
			}
			map.addOverlay(markers[id]);
			createInfobox(id);
			GEvent.addListener(markers[id], "click", function() {
				selectedSatellite = id;
				map.openInfoWindow(markers[id].getLatLng(), popups[id]);
			});
			GEvent.addListener(markers[id], "mouseover", function() {
				highlightTrack(id);
				highlightFootprint(id);
			});
			GEvent.addListener(markers[id], "mouseout", function() {
				dimTrack(id);
				dimFootprint(id);
			});
		});
	}
}

function destroyMarker(id) {
	map.removeOverlay(markers[id]);
	delete markers[id];
}

function highlightMarker(id) {
	if ($("input#set_shownames")[0].checked) {
		markers[id].setImage("server.py/label?mode=flash&id=" + id);
	}
}

function dimMarker(id) {
	if ($("input#set_shownames")[0].checked) {
		markers[id].setImage("server.py/label?mode=normal&id=" + id);
	}
}

function toggleMarkerMode() {
  if (typeof map.addOverlay != "function") {
    return;
  }
	for (var id in markers) {
		var coord = markers[id].getLatLng();
		var title = markers[id].getTitle();
		destroyMarker(id);
		createMarker(id, false);
	}
}
