var geocoder = null;
var map = null;
var markerOptions = null;
var locations = null;
var points = new Array();

function map_init() {
	
	if (GBrowserIsCompatible()) {

		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GSmallMapControl());
		geocoder = new GClientGeocoder();
 		var markerIcon = new GIcon(G_DEFAULT_ICON);
		markerIcon.image = pathToMarker;
		markerIcon.shadow = '';
		markerIcon.iconSize = new GSize(markerWidth, markerHeight);
		markerIcon.iconAnchor = new GPoint(markerWidth/2,markerHeight/2);
		markerOptions = { icon: markerIcon };
		centerMap(initialLocation, initialZoom, addTags);
		// setTimeout("addTags()", 200);	
				
	}

}

function centerMap(addr, zoom, onCompleteFunc) {
		
	if (geocoder) {

		geocoder.getLatLng(
			addr,
			function(point) {
				if (point) {
					map.setCenter(point, zoom);
				} else {
					var defPoint = new GLatLng(37.688889, -97.336111);
					map.setCenter(defPoint, initialZoom);
				}
				if (onCompleteFunc) {
					onCompleteFunc();
				}
			}
		);
		
	}

}

function recenterMap() {

	var mapEntry = document.getElementById("map_entry");

	if (mapEntry != null && typeof mapEntry != undefined) {
		centerMap(mapEntry.value, locationZoom, checkForPointsInViewport);
	}

}		 

function addTags(locs) {

	try {

		GDownloadUrl(pathToLocationFile, handleAddTags);

	} catch (e) {}

}

function handleAddTags(response, status) {

	if (response != null && status == '200') {

		locations = response.split("\n");

		addTag(0);

	}

}

function addTag(idx) {

	var addr = locations[idx];

	if (geocoder) {

		geocoder.getLatLng(
			addr,
			function(point) {
				if (point) {
					var marker = new GMarker(point, markerOptions);
					map.addOverlay(marker);
					points.push(point);
				}
				if (idx < locations.length - 1) {
					setTimeout("addTag(" + (idx + 1) + ")", 200);
				}
			}
		);

	}

}

function checkForPointsInViewport() {

	var arePointsVisible = false;
	var bounds = map.getBounds();

	for (var i = 0; i < points.length; i++) {

		if (bounds.containsLatLng(points[i])) {

			arePointsVisible = true;
			break;

		}

	} 

	if (!arePointsVisible) {

		var mapErrorLayer = document.getElementById("map_error");
		if (mapErrorLayer) {
			mapErrorLayer.style.display = 'block';
		}
	}

}

function closeMapError() {

	var mapErrorLayer = document.getElementById("map_error");
	if (mapErrorLayer) {
		mapErrorLayer.style.display = 'none';
	}

}
