var map;
var centerLatitude = -30.559482;
var centerLongitude = 22.937506; 
var startZoom = 1;
_mPreferMetric=true;
var icon = new GIcon();
var deselectCurrent = function() {};

 
function initializePoint(pointData) {
	var point = new GLatLng(pointData.latitude, pointData.longitude);
	var marker = new GMarker(point, icon);
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	var visible = false;
	listItemLink.href = "#";
	listItemLink.innerHTML = '<strong>' + pointData.Name + ", " + pointData.address + '</strong>' + "<span>" + pointData.city + ', ' + pointData.Phone + ", " + pointData.schooltype + '</span>';
	
	var focusPoint = function() {
		deselectCurrent();
		
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		marker.openInfoWindowHtml(pointData.Name + "<br>" + pointData.address);
		draw(point);
		map.panTo(point);
		

		return false;
	}
 
	GEvent.addListener(marker, 'click', focusPoint);	
	listItemLink.onclick = focusPoint;
 
	pointData.show = function() {
		if (!visible) {
			document.getElementById('sidebar-list').appendChild(listItem);
			map.addOverlay(marker);
			
			visible = true;
			

		}
	}
	pointData.hide = function() {
		if (visible) {
		//
			document.getElementById('sidebar-list').removeChild(listItem);
			map.removeOverlay(marker);
			visible = false;
		}
	}

	pointData.show();
}
 
function initializeSortTab(type) {
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
 
	listItemLink.href = "#";
	listItemLink.innerHTML = type;
	listItemLink.onclick = function() {
		changeBodyClass('standby', 'loading');
 
		for(id in markers) {
			if (markers[id].type == type || 'All' == type)
				markers[id].show();
			else
				markers[id].hide();	
		}
 
		changeBodyClass('loading', 'standby');
 
		return false;
	}
 
	document.getElementById('filters').appendChild(listItem);
}
 
function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}
 
function handleResize() {
	var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 30;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height + 'px';
}
 
function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}
 
function init() {
	var type;
	var allTypes = { 'All':[] };
	
	document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	handleResize();
	
	xmlhttp = GXmlHttp.create();
	xmlhttp.open('GET', 'data.txt', true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status != 200)
				setAlertText('Could not access map data.');
			else
			{
				var responseText = xmlhttp.responseText;
				markers = eval(responseText);
				if (!markers)
					setAlertText('Map data error.');
				else
					initData();
			}
		}
	}
	xmlhttp.send(null);
}
 
function setAlertText(str) {
	document.getElementById('alert').innerHTML = '<p>' + str + '</p>';
}
 
function initData() {
	var type;
	var allTypes = { 'All':[] };
 
	map = new GMap(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl(10));
	map.addControl(new GScaleControl(300));
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	
// Create our "tiny" marker icon
icon.image = "mm_20_red.png";
icon.shadow = "mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);
 
	for(id in markers) {
		initializePoint(markers[id]);
		allTypes[markers[id].type] = true;
	}
	
	for(type in allTypes) {
		initializeSortTab(type);
	}
	
	changeBodyClass('loading', 'standby');
}

////pan and zoom to fit

var bounds = new GLatLngBounds();
function fit(){
map.panTo(bounds.getCenter()); 
map.setZoom(map.getBoundsZoomLevel(bounds));
}


///Geo

var geocoder = new GClientGeocoder();

function showAddress(address){
geocoder.getLatLng(address,function(point){
if(!point){
document.getElementById('haku').style.color = 'red';
}
else{
draw(point);
map.panTo(point);
document.getElementById('haku').style.color = 'black';
}})}

// Esa's Auto ZoomOut

function esasZoomOut(){
var paragraphs = map.getContainer().getElementsByTagName('p').length;
//GLog.write(paragraphs);
if(paragraphs > 6){
map.zoomOut();
}}
var interval = setInterval("esasZoomOut()",500);

	//calling circle drawing function
	function draw(point){
	//map.clearOverlay(poly);
	bounds = new GLatLngBounds();
	var givenRad = 3;
	var givenQuality = 40;
	var centre = point;
	//var centre = pnt 
	drawCircle(centre, givenRad, givenQuality);
	fit();
	}

	////////////////////////// circle///////////////////////////////
	
function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{
// Esa 2006
	//calculating km/degree
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + 
	(radius/lngConv * Math.sin(i * Math.PI/180)));
	points.push(pint);
	bounds.extend(pint); //this is for fit function
	}
	points.push(points[0]); // Closes the circle, thanks Martin
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	map.addOverlay(poly);
}
 
window.onresize = handleResize;
window.onload = init;