
var map;
var numIcons = 0;
var points = new Array();

function init() {
	resizeMap();
	
	map = new GMap2($("map"));
	map.setCenter(new GLatLng(48.5166043, -95.625), 4);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.enableDoubleClickZoom();
	
	GEvent.addListener(map, 'click', function(overlay, point) {
		if (point) {
			map.addOverlay(createMarker(point, numIcons));
			sidebar = document.getElementById('results');
			sidebar.innerHTML = sidebar.innerHTML+"<div id='point"+numIcons+"'>"+point+"</div>";
			numIcons++;
			clearSelections();
		}
	});
		
}

function createMarker(point, number) {
	var marker = new GMarker(point, {draggable: true});
	var html = "<div class='bubble'><h3>Delete?</h3><input type='button' onclick='removeMarker("+numIcons+")' value='Yes' /> <input type='button' onclick='map.closeInfoWindow()' value='No' /></div>";
	
	GEvent.addListener( marker, "click", function() {
		//add a behaviour to the list items to 'select' them when the GPoint is selected
		clearSelections();
		div = document.getElementById("point"+number);
		div.className = "selected";
		marker.openInfoWindowHtml(html);
	});
	
	GEvent.addListener(marker, "dragend", function() {
		div = document.getElementById("point"+number);
		div.innerHTML = marker.getPoint();
	});
	
	points[number] = marker;
	return marker;
}

function removeMarker(markerNum){
	div = document.getElementById("point"+markerNum);
	div.parentNode.removeChild(div);
	map.removeOverlay(points[markerNum]);
	map.closeInfoWindow();
}

function clearSelections(){
	var divs = $('results').getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++) {
		divs[i].className = '';
	}
}

function clear(){	
	map.clearOverlays();
	$('results').innerHTML = "";
}

function resizeMap() {
	var height = getWindowSize();
	var map_height = height - 80;
	var result_height = height - 270;
	$("map").style.height = map_height + 'px';
	$('results').style.height = result_height + 'px';
}

function getWindowSize()
{
	var height = 0;
	if(self.innerHeight) {
			height = self.innerHeight;
	}else if(document.documentElement && document.documentElement.clientHeight) {
			height = document.documentElement.clientHeight;
	}else {
			height = document.body.clientHeight;
	}
	return height;
}

function $(id) {
	return document.getElementById(id);
}
		
window.onload = init;
window.onresize = resizeMap;
window.onunload = GUnload;
