var gMapCircle;
var markers = [];
var numMarkers=0;

function createGoogleMap(divName,typeControl,navControl,scaleControl,streetview,centerLat,centerLong) {
	if (typeControl==undefined) typeControl=true;
	if (navControl==undefined) {
		navControlBool=true;
		navControlType=google.maps.NavigationControlStyle.DEFAULT;
	} else if (navControl!='none') {
		navControlBool=true;
		navControlType=navControl;
	}
	if (scaleControl==undefined) scaleControl=true;
	if (streetview==undefined) streetview=true;
	if (centerLat==undefined) centerLat=39.833333333;
	if (centerLong==undefined) centerLong=-98.58333333;

	var myLatlng = new google.maps.LatLng(centerLat,centerLong);
	var mapOptions = {
		center: myLatlng,
		zoom: 14,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		streetViewControl: streetview,
		navigationControl: navControlBool,
		navigationControlOptions: {
			style: navControlType
		},
		mapTypeControl: typeControl,
		scaleControl: scaleControl
	};
	var map = new google.maps.Map(getElem(divName), mapOptions);
	gMapCircle = new google.maps.Circle({radius: 10, center: myLatlng, fillColor: '#88f', strokeColor: '#448'}); 
return map;
}

function removeMarkerFromMap(marker) {
	marker.setMap(null);
}

function removeAllMarkersFromMap() {
	for (var i=numMarkers-1;i>=0;i--) {
		removeMarkerFromMap(markers[i]);
	}
	markers.length=0;
	numMarkers=markers.length;
	removeCircleFromMap(gMapCircle	);
}

function bringFrontMarker(idx) {
	for (var i=0;i<numMarkers;i++) {
		markers[i].setZIndex(1);
	}
	markers[idx].setZIndex(numMarkers+1);
}

function addPointToMap(map,hsInfo,bounds,marker) {
	if (marker==undefined) marker='green';
	var centerLat=40;
	var centerLong=-89;

	var myLatlng = new google.maps.LatLng(hsInfo['CLt'],hsInfo['CLn']);
	var image = new google.maps.MarkerImage(rootpath+'/images/map/'+marker+'.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(20, 34),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(9,34));

	var shadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
		// The shadow image is larger in the horizontal dimension
		// while the position and offset are the same as for the main image.
		new google.maps.Size(37, 34),
		new google.maps.Point(0,0),
		new google.maps.Point(9,35));

	var marker = new google.maps.Marker({
		position: myLatlng, 
		map: map, 
		title: hsInfo['Name']+'',
		icon: image,
		shadow: shadow,
		flat: false
	});
	markers[markers.length]=marker;
	numMarkers++;
	bounds.extend(myLatlng);

return bounds;
}

function addCircleToMap(map, radius, lat, lng) {
	var myLatlng = new google.maps.LatLng(lat,lng);
	var zm=map.getZoom();
	var rad=radius/80*Math.pow(2,(21-zm));
	gMapCircle.setRadius(rad);	//in meters
	gMapCircle.setCenter(myLatlng);
	gMapCircle.setMap(map);
}

function removeCircleFromMap(circ) {
	if (circ==undefined) circ=gMapCircle;
	circ.setMap(null);	//IE8, at least, doesn't like this if you very quickly mouse over several spots.  It's like IE8 doesn't keep up and then forgets what to do
}

function setBoundsToMarkers(map) {
	var bounds = new google.maps.LatLngBounds();
	var myLatlng = new google.maps.LatLng(39.833333333,-98.58333333);
	if (numMarkers>0) {
		map.setCenter(markers[0].position);
		map.setZoom(14);
		for (var i=0;i<numMarkers;i++) {
			bounds.extend(markers[i].position);
		}
		map.fitBounds(bounds);
	} else {
		map.setCenter(myLatlng);
		map.setZoom(4);		
	}
}







function createDirectionsMap(divMapName,divDirName,points) {
// this expects that points is an array of 2 - 25 points.  
// points[0] should be the start from location, the last point should be the final destination.  
// all other points between (if any) are in order of stops

	var map=createGoogleMap(divMapName);
	var directionsPanel = document.getElementById(divDirName);
	directionsPanel.innerHTML='';
	var statusdiv=document.getElementById('dirAddressResults');
	setDiv('dirAddressResults',null,null,'none');
	statusdiv.innerHTML='';

	if (points.constructor.toString().indexOf("Array") == -1) {	//points is not an array
		if (points=="") {
			setDivText('dirAddressResults','No address was specified as a starting location.');
		}
	}
	else {
		if (points[0]=="" || points[0]=="0,0") {
			setDivText('dirAddressResults','No address was specified as a starting location.');
		}
	}

	if (statusdiv.innerHTML=='') {
		var directions = new GDirections(map, directionsPanel);
		GEvent.addListener(directions, "error", function() {var statusdiv=document.getElementById('dirAddressResults'); setDivText('dirAddressResults',interpretGoogleError(this.getStatus())); if(!statusdiv.innerHTML=='' && statusdiv.innerHTML.indexOf('uccess')<0) setDiv('dirAddressResults',null,null,'block');});
		setTimeout(function() {directions.loadFromWaypoints(points);},100);
	}
}

function updateMap(points,bubbleCaption,bubbleText,marker,id) {	
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	var map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(0,0),0);
	var bounds = new GLatLngBounds();
	map.addControl(new GMapTypeControl());
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl());

	numPoints=points.length;		
	for(var i=0; i<numPoints; i++) {
		var ltlng=points[i].split(",");
		var point = new GLatLng(parseFloat(ltlng[0]),parseFloat(ltlng[1]));
		bounds.extend(point);
		var gMarker = createMarker(point,bubbleCaption[i],bubbleText[i],marker[i],baseIcon);
		if (id[i]>0) {
			var link="http://www.beermagnet.com/hs/hotspot.php?id=" + id[i];
			GEvent.addListener(gMarker, "click", function() {window.location=link;});
		}
		map.addOverlay(gMarker);
	}
	map.setZoom(map.getBoundsZoomLevel(bounds));
	if (numPoints > 1) map.setCenter(bounds.getCenter());
	else map.setCenter(bounds.getCenter(),13);
}
	
function createMarker(point, caption, html, markername, baseIcon) {
	var icon = new GIcon(baseIcon);
	icon.image = rootpath + "/images/map/"+markername;
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, "mouseover", function() { olMouseCapture(); createOverDIV('mapPin','mapOverDIV','<h1>' + caption + '</h1><div>' + html + '</div>'); });
	GEvent.addListener(marker, "mouseout", function() { disableMouseMove(); removeElem('mapPin'); });
	return marker;
}

function interpretGoogleError(status) {
	var strCnst=new Array();
	var intCode=new Array();
	var strDesc=new Array();
	var strDsc2=new Array();

	strCnst[0]="G_GEO_SUCCESS";
	intCode[0]="200";
	strDesc[0]="No errors occurred; the address was successfully parsed and its geocode has been returned.";
	strDsc2[0]="Request successful";
	strCnst[1]="G_GEO_BAD_REQUEST";
	intCode[1]="400";
	strDesc[1]="A directions request could not be successfully parsed. For example, the request may have been rejected if it contained more than the maximum number of waypoints allowed.";
	strDsc2[1]="Error: Invalid address request.  It may be that too many waypoints were requested.";
	strCnst[2]="G_GEO_SERVER_ERROR";
	intCode[2]="500";
	strDesc[2]="A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.";
	strDsc2[2]="Error: An error occurred with the Google server.";
	strCnst[3]="G_GEO_MISSING_QUERY";
	intCode[3]="601";
	strDesc[3]="The HTTP q parameter was either missing or had no value. For geocoding requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.";
	strDsc2[3]="Error: No address specified.";
	strCnst[4]="G_GEO_UNKNOWN_ADDRESS";
	intCode[4]="602";
	strDesc[4]="No corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect.";
	strDsc2[4]="Error: Unknown address";
	strCnst[5]="G_GEO_UNAVAILABLE_ADDRESS";
	intCode[5]="603";
	strDesc[5]="The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.";
	strDsc2[5]="Error: Directions cannot be given, possibly due to legal or contractual reasons";
	strCnst[6]="G_GEO_UNKNOWN_DIRECTIONS";
	intCode[6]="604";
	strDesc[6]="The GDirections object could not compute directions between the points mentioned in the query. This is usually because there is no route available between the two points, or because we do not have data for routing in that region.";
	strDsc2[6]="Error: Directions could not be computed";
	strCnst[7]="G_GEO_BAD_KEY";
	intCode[7]="610";
	strDesc[7]="The given key is either invalid or does not match the domain for which it was given.";
	strDsc2[7]="Error: Google has rejected the request due to authentication errors";
	strCnst[8]="G_GEO_TOO_MANY_QUERIES";
	intCode[8]="620";
	strDesc[8]="The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time. If you're sending multiple requests in parallel or in a tight loop, use a timer or pause in your code to make sure you don't send the requests too quickly.";
	strDsc2[8]="Error: Google has rejected the request due to limiting.";

	var i;
	for (i=0;i<intCode.length;i++) {
		if (intCode[i]==status.code) {
			break;
		}
	}

	return strDsc2[i];
}
