var markerCnt;
var map;
var poly;
var directions;
var directionsPanel;
var gDirections;
var centerLatitude = 44.241;
var centerLongitude = -100.287; 
var startZoom = 7;
var bounds = new GLatLngBounds();
var start_set = false;
var start_coordinates;
var pointData = [];
var isIE = document.all;


var new_window;


var icon = [];
	icon = new GIcon();
	icon.image = "http://maps.google.com/mapfiles/kml/pal5/icon10.png";
	icon.shadow = "http://maps.google.com/mapfiles/kml/pal5/icon10s.png";
	icon.iconSize = new GSize(24,24);
	icon.shadowSize = new GSize(48,24);
	icon.iconAnchor = new GPoint(16,24);
	icon.infoWindowAnchor = new GPoint(8,16);
	
var gDirections=new GDirections(null, document.getElementById("route-directions"));
var deselectCurrent = function() {};

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}

function initializePoint(pointData) {
	if(pointData.latitude == 0) { return; }
	var visible = false;
	var point = new GLatLng(pointData.latitude, pointData.longitude);
	var listItem = document.createElement('li');
	listItem.id = pointData.sid + '/';
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = 'javascript:void(0);';


	listItemLink.innerHTML = '<em>' + pointData.address + '</em><span>' + pointData.city + ', ' + pointData.state + ' ' + pointData.zip + '</span><span style="font-size:x-small;"><i>' + pointData.desc2 + '...</i></span>';

	var infoUrl = 'map_item.php?id=' + pointData.sid;
	var marker = new GMarker(point,icon);
	
	var html = '<div id="infoWindow" style="margin-right: 5px; padding: 0px;">' + 
		'<div style="width:320px; border-bottom:1px solid #333; padding: 5px 0px 5px 0px;">' +
			'<span class="title">'+ pointData.address +'</span><br />' +
			pointData.city + ', ' + pointData.state + ' ' + pointData.zip +
			'<div style="margin-top:10px;">' + pointData.sdate + '</div>' +
		'</div>' +
		'<div style="width:420px; border-bottom:1px solid #333; padding: 5px 0px 5px 0px;">' + pointData.desc + '</div>' +
		'<div style="width:420px; padding: 5px 0px 5px 0px;">' +
			'Get directions <strong>to here</strong> from...' +
			'<form style="margin:0;padding:0;" action="http://maps.google.com/maps" method="get" target="_blank">' +
				'<input style="width:270px;" type="text" size="10" maxlength="40" name="saddr" id="saddr" value="" /><input value="Get Directions" type="submit">' +
				'<input type="hidden" name="daddr" value="' + pointData.address + ',' + pointData.city + ',' + pointData.state + ',' + pointData.zip + '"/>' +
			'</form>' +
		'</div>' +
		'<div id="infoWindowMenu" style="width:320px; text-align:right; padding: 5px 0px 5px 0px;">' +
			'<a style="float:left;" href="javascript:void(0);" onclick="addRoutePoint(\'' + pointData.sid + '\',\'' + pointData.address + '\',\'' + pointData.city + '\',\'' + pointData.state + '\',\'' + pointData.zip + '\',\'' + pointData.latitude + '\',\'' + pointData.longitude + '\');">add route +</a>' +
			'<a style="float:right;" href="javascript:void(0);" onclick="map.getInfoWindow().maximize();">more info &raquo;</a>' +
			'<br style="clear:both;" />' +
		'</div>' +
		'</div>';
	
		markerCnt += 1;

	
	
	/*
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		marker.openInfoWindowHtml(html, {maxUrl:infoUrl});
		map.panTo(point);
		return false;
	}
*/
	
	// ADDED ON 3/16/08 BY TJO
	// NEW METHOD OF HANDELING MAX WINDOWS
	var focusPoint = function() {
		var maxContentDiv = document.createElement('div');
		maxContentDiv.innerHTML = 'Loading...';
		
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		
		marker.openInfoWindowHtml(html,
			{maxContent: maxContentDiv, 
			maxTitle: pointData.address});
			map.panTo(point);
		
		var iw = map.getInfoWindow();
		GEvent.addListener(iw, "maximizeclick", function() {
			GDownloadUrl(infoUrl, function(data) {
				maxContentDiv.innerHTML = data;
			});
		});
		return false;
	}
	
	GEvent.addListener(marker, 'click', focusPoint);
	listItemLink.onclick = focusPoint;
	
	pointData.show = function() {
		if (!visible) {
			document.getElementById('sidebar-list').appendChild(listItem);
			map.addOverlay(marker);
			bounds.extend(point);
			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 = "javascript:void(0);";
	listItemLink.title = "show " + type;
	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 - 112;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height - 220 + 'px';
	document.getElementById('sidebar-route').style.height = height - 35 + 'px';
}

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}

function calNavigate(month,year,day,view) {
	var url = "calendar.php?month="+month+"&year="+year+"&day="+day+"&view="+view;
	if(window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.open("GET", url, true);
	req.onreadystatechange = callback;
	req.send(null);
}

function callback() {
	if(req.readyState == 4) {
		if(req.status == 200) {
			response = req.responseText;
			document.getElementById("calendar").innerHTML = response;
		} else {
			alert("There was a problem retrieving the calendar:\n" + req.statusText);
		}
	}
}

function getRoutes() {
	var routeList = document.getElementById("route-list");
	var myPoints = new Array();
	map.closeInfoWindow();
	if (routeList.hasChildNodes()) {
		var children = routeList.childNodes;
		for (var i = 0; i < children.length; i++) {
			myPoints.push(children[i].lastChild.innerHTML);
		};
	};
	setTimeout(function(){
		directions.loadFromWaypoints(myPoints,{preserveViewport:true,getPolyline:true,getSteps:true,locale:"en_US"});
	},500);
	printRoute(myPoints);
}

function addRoutePoint(id,address,city,state,zip,lat,lon) {
	var routeListItem = document.createElement('li');
	routeListItem.id = id;
	routeListItem.innerHTML = '<span>' + address + '<br />' + city + ', ' + state + ' ' + zip + '</span>&nbsp;[&nbsp;<span><a href="javascript:void(0);" onclick="remRoutes(\'' + routeListItem.id + '\');">X</a>&nbsp;]</span><span class="noShow">' + address + ', ' + city + ', ' + state + ' ' + zip + '@' + lat + ',' + lon + '</span>';
	document.getElementById('route-list').appendChild(routeListItem);
	changeBodyClass('sidebar-right', 'nosidebar');
	map.closeInfoWindow();
	getRoutes();
}	

function remRoutes(id) {
	var element = document.getElementById("route-list");
	var nested = document.getElementById(id); 
	var throwAwayNode = element.removeChild(nested);
	map.closeInfoWindow();
	getRoutes();
}

function remAllRoutes() {
	var element = document.getElementById("route-list");
	while (element.firstChild) { element.removeChild(element.firstChild); }
	map.closeInfoWindow();
	directions.clear();
	getRoutes();
}

function printRoute(myPoints) {
	var theRouteLink = document.getElementById('print_route');
	var myRoute = '';
	for (var i = 0; i < myPoints.length; i++) {
		if(i > 0)
			myRoute = myRoute + '+to:+' + myPoints[i];
		else
			myRoute = myRoute + 'http://maps.google.com/maps?f=q&hl=en&geocode=&q=from:+' + myPoints[i];
	};
	myRoute = myRoute + '&ie=UTF8&z=13&om=1&pw=2';
	theRouteLink.href = 'javascript:void(0)';
	theRouteLink.innerHTML = 'print';
	theRouteLink.onclick = function() {
		if(myPoints.length != 0) {
			window.open(myRoute,'RouteList','width=800,height=500,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
		}
	}
}

function mapDetail(lat,lon,zoom) {
	if (GBrowserIsCompatible()) {
		var point = new GLatLng(lat, lon);
		var smallmap = new GMap2(document.getElementById("mapdetail"));
		smallmap.addControl(new GSmallMapControl());
		smallmap.setCenter(new GLatLng(point), zoom);
		smallmap.addOverlay(new GMarker(point));
	}
}



function init() {
	var type;
	var allTypes = { 'All':[] };
		
	document.getElementById('button-sidebar-route').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-calendar').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	
	handleResize();
	
	map = new GMap2(document.getElementById("map"));
	map.enableDoubleClickZoom();
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl(new GSize(133,75)));
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	directionsPanel = document.getElementById("route-route");
	directions = new GDirections(map, directionsPanel);
	
	for(id in markers) {
		initializePoint(markers[id]);
		allTypes[markers[id].type] = true;
	}

	for(type in allTypes) {
		initializeSortTab(type);
	}
	
	map.setZoom(map.getBoundsZoomLevel(bounds));
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));
	
	changeBodyClass('loading', 'standby');
	calNavigate(month,year,day,view);
	
}



window.onresize = handleResize;
window.onload = init;