var icon;
var map;
var defaultPoints=100;
var mapType = "state";
var infoWindow = "0";
var default_zoom;

//Multidim array to relate state Abbreviations to name, latitude and longitude

var state_list = new Array();
state_list["AL"]= new Array("Alabama",32.7990,-86.8073);  
state_list["AK"]= new Array("Alaska", 61.3850, -152.2683);
state_list["AZ"]= new Array("Arizona",33.7712,-111.3877);  
state_list["AR"]= new Array("Arkansas",34.9513,-92.3809);  
state_list["CA"]= new Array("California",36.1700,-119.7462);  
state_list["CO"]= new Array("Colorado",39.0646,-105.3272);  
state_list["CT"]= new Array("Connecticut",41.5834,-72.7622);  
state_list["DE"]= new Array("Delaware",39.3498,-75.5148);  
state_list["DC"]= new Array("District Of Columbia",38.8964,-77.0262);  
state_list["FL"]= new Array("Florida",27.8333,-81.7170);  
state_list["GA"]= new Array("Georgia",32.9866,-83.6487);  
state_list["HI"]= new Array("Hawaii",21.1098,-157.5311);  
state_list["ID"]= new Array("Idaho",44.2394,-114.5103);  
state_list["IL"]= new Array("Illinois",40.3363,-89.0022);  
state_list["IN"]= new Array("Indiana",39.8647,-86.2604);  
state_list["IA"]= new Array("Iowa",42.0046,-93.2140);  
state_list["KS"]= new Array("Kansas",38.5111,-96.8005);  
state_list["KY"]= new Array("Kentucky",37.6690,-84.6514);  
state_list["LA"]= new Array("Louisiana",31.1801,-91.8749);  
state_list["ME"]= new Array("Maine",44.6074,-69.3977);  
state_list["MD"]= new Array("Maryland",39.0724,-76.7902);  
state_list["MA"]= new Array("Massachusetts",42.2373,-71.5314);  
state_list["MI"]= new Array("Michigan",43.3504,-84.5603);  
state_list["MN"]= new Array("Minnesota",45.7326,-93.9196);  
state_list["MS"]= new Array("Mississippi",32.7673,-89.6812);  
state_list["MO"]= new Array("Missouri",38.4623,-92.3020);  
state_list["MT"]= new Array("Montana",46.9048,-110.3261);
state_list["NE"]= new Array("Nebraska",41.1289,-98.2883);
state_list["NV"]= new Array("Nevada",38.4199,-117.1219);
state_list["NH"]= new Array("New Hampshire",43.4108,-71.5653);
state_list["NJ"]= new Array("New Jersey",40.3140,-74.5089);
state_list["NM"]= new Array("New Mexico",34.8375,-106.2371);
state_list["NY"]= new Array("New York",42.1497,-74.9384);
state_list["NC"]= new Array("North Carolina",35.6411,-79.8431);
state_list["ND"]= new Array("North Dakota",47.5362,-99.7930);
state_list["OH"]= new Array("Ohio",40.3736,-82.7755);  
state_list["OK"]= new Array("Oklahoma",35.5376,-96.9247);  
state_list["OR"]= new Array("Oregon",44.5672,-122.1269);  
state_list["PA"]= new Array("Pennsylvania",40.5773,-77.2640);  
state_list["RI"]= new Array("Rhode Island",41.6772,-71.5101);  
state_list["SC"]= new Array("South Carolina",33.8191,-80.9066);  
state_list["SD"]= new Array("South Dakota",44.2853,-99.4632);
state_list["TN"]= new Array("Tennessee",35.7449,-86.7489);  
state_list["TX"]= new Array("Texas",31.1060,-97.6475);  
state_list["UT"]= new Array("Utah",40.1135,-111.8535);  
state_list["VT"]= new Array("Vermont",44.0407,-72.7093);  
state_list["VA"]= new Array("Virginia",37.7680,-78.2057);  
state_list["WA"]= new Array("Washington",47.3917,-121.5708);  
state_list["WV"]= new Array("West Virginia",38.4680,-80.9696);  
state_list["WI"]= new Array("Wisconsin",44.2563,-89.6385);  
state_list["WY"]= new Array("Wyoming",42.7475,-107.2085);


var showTestInfo = (getQueryString("td") ) ? true : false;

function initialize() 
	{
	var default_longitude = -97;
	var default_latitude = 38.5;
	default_zoom = 13;
	
	if (GBrowserIsCompatible()) 
		{
		map = new GMap(document.getElementById("map_canvas"));
		map.centerAndZoom(new GPoint(default_longitude,default_latitude), default_zoom);
		geocoder = new GClientGeocoder();
		}
	
	icon = new GIcon();
	icon.image = "/images/map_the_pledge/droplet.png";
	icon.shadow = "/images/map_the_pledge/shadow50.png";
	icon.iconSize = new GSize(20, 34); 
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());

	showMapBounds(map);
	GEvent.addListener(map, "zoomend", function(oldLevel,newLevel){ 	
													if ((oldLevel == 5) && (newLevel == 6)) {
														map.setZoom(9);
													} else if ((oldLevel == 9) && (newLevel == 8)) {
														map.setZoom(5);
													} else {
														showMapBounds (map);
													}
												} ); 
	}

function showMapBounds (map)
	{

	GEvent.clearListeners(map, "moveend")
	if (map.getZoom() <= 7) {
		mapType = "state";
	} else {
		mapType = "city";
		GEvent.addListener(map, "moveend", function() { if (infoWindow == "0") {
                                                            showMapBounds (map);
                                                    } else {
                                                        infoWindow = "0";
                                                    } } ); 
	}
		
	clearMap();
	var center = map.getCenter();
	
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();

	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();

	var swLon = southWest.lng();
	var swLat = southWest.lat();
	var neLon = northEast.lng();
	var neLat = northEast.lat();

	var myMessage = "Southwest Lon: " + swLon;
	myMessage += "\n<br />Southwest Lat: " + swLat;
	myMessage += "\n<br /><br />" + "Northeast Lon: " + neLon;
	myMessage += "\n<br />Northeast Lat: " + neLat;
	myMessage += "\n<br /><br />Long Span: " + lngSpan;
	myMessage += "\n<br />Lat Span: " + latSpan;

	if (showTestInfo) { document.getElementById("coords").innerHTML =  myMessage; }
	url  =  "code/php/getXML.php?swLat="+swLat+"&swLon="+swLon+"&neLat="+neLat+"&neLon="+neLon+"&count="+defaultPoints+"&mapType="+mapType;
	loadXMLDoc(url);
	}

function loadXMLDoc(url) 
	{
			
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) 
		{
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
		} 
	// branch for IE/Windows ActiveX version
	else if (window.ActiveXObject) 
		{
		isIE = true;
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) 
			{
			req.onreadystatechange = processReqChange;
 			req.open("GET", url, true);
			req.send();
			}
		}
	}

// handle onreadystatechange event of req object
function processReqChange()
	{
	// only if req shows "loaded"
	if (req.readyState == 4) 
		{
		// only if "OK"
		if (req.status == 200)
			{
			//clearTopicList();
			//buildTopicList();
			//alert(url);
			buildTopicList();
			} 
		else 
			{
			alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	}

function clearMap()
	{
	map.clearOverlays();
	polyPoints = [];
	//document.getElementById("coords").value =  "&lt;-- Click on the map to digitize!";
	} 


// fill Topics select list with items from
// the current XML document
function buildTopicList() 
	{
	
	var items = req.responseXML.getElementsByTagName("pledge");
	// loop through <item> elements, and add each nested
	// <title> element to Topics select element
	//alert(items.length);

	
	alertMarkers="";
	//GEvent.clearInstanceListeners(map);

	if (mapType == "city") {
		for (var i = 0; i < items.length; i++) 
			{
			var lon = getElementTextNS("", "longitude", items[i], 0);
			var lat = getElementTextNS("", "latitude", items[i], 0);
			if (getElementTextNS("", "city", items[i], 0) == "NULL") {
				continue;
			} else {
				var city = getElementTextNS("", "city", items[i], 0);
			}
			var state = getElementTextNS("", "state", items[i], 0);
			var bottle_count = getElementTextNS("", "bottle_count", items[i], 0);
	
			var message = "<div class='bubble'><div class=\"bigZip\">" + city + ", " + state + "</div><p>Based on the pledges we've received<br /> so far, <span class=\"red\">" + bottle_count + "</span> bottles have been saved <br />in this city.</p><p><img src=\"images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"take_the_pledge.php\">Make your pledge today</a>.</p></div>"; 
			if (lat!=0 && lon!=0)
				{	
				var newPoint = new GPoint(lon, lat);
				var newMarker = new GMarker(newPoint, icon);
				newMarker.msg = message;
				map.addOverlay(newMarker);
				//mgr.addMarker(newMarker, 0, 15);
				GEvent.addListener(newMarker, "click", function() { infoWindow = "1"; this.openInfoWindowHtml(this.msg); });
				}
			}
	} else {
		
		for (var i = 0; i < items.length; i++) {
			var state = getElementTextNS("", "state", items[i], 0);
			
			if (state_list[state]) {
				state_name = state_list[state][0];
				var bottle_count = getElementTextNS("", "bottle_count", items[i], 0);	
				var lat = state_list[state][1]; 
				var lon = state_list[state][2]; 
				address = state + ", USA";
				var message = "<div class='bubble'><div class=\"bigZip\">" + state_name + "</div><p>Based on the pledges we've received<br /> so far, <span class=\"red\">" + bottle_count + "</span> bottles have been saved <br />in this state.</p><p><img src=\"images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"take_the_pledge.php\">Make your pledge today</a>.</p></div>"; 
					var newPoint = new GPoint(lon, lat);
					var newMarker = new GMarker(newPoint, icon);
					newMarker.msg = message;
					map.addOverlay(newMarker);
					GEvent.addListener(newMarker, "click", function() { this.openInfoWindowHtml(this.msg); });
		 	}
			
		}
		
	}

	// clear detail display
	alertMarkers = (alertMarkers.length>0) ? alertMarkers : "No Pledges in this view."
	if (showTestInfo) { document.getElementById("pledgePoints").innerHTML =  alertMarkers; }
	}


// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) 
	{
	var result = "";
	if (prefix && isIE)
		{
		// IE/Windows way of handling namespaces
		result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
		} 
	else 
		{
		// the namespace versions of this method 
		// (getElementsByTagNameNS()) operate
		// differently in Safari and Mozilla, but both
		// return value with just local name, provided 
		// there aren't conflicts with non-namespace element
		// names
		result = parentElem.getElementsByTagName(local)[index];
		}
	if (result) 
		{
		// get text, accounting for possible
		// whitespace (carriage return) text nodes 
		if (result.childNodes.length > 1)
			{
			return result.childNodes[1].nodeValue;
			} 
		else 
			{
				if (result.childNodes.length == 0) {
					return "NULL";
				} else {
					return result.firstChild.nodeValue;
				}
			}
		} 
	else
		{
		return "n/a";
		}
	}
	

function getQueryString(arg)
	{
	var _d = document.location.toString();
	if(_d.indexOf("?")>0)
		{
		var _e = _d.split("?")[1];
		var _parms = new Array();
		var _valus = new Array();
		// parameters must have a &
		var _f = _e.split("&");
		for(var i=0;i<_f.length;i++) 
			{
			if(_f[i].split("=")[0] == arg)
				{
		  		var qval = _f[i].split("=")[1];
		  		var qval_idx = qval.indexOf("#");
		  		if (qval_idx > -1)  { qval = qval.substring(0, qval_idx); }
				return unescape(qval.replace(/\+/," "));
				}
			}
		}
	return "";
	}


function showAddress(address)
	{
	mapType = "city";
	address = address + ", USA";
	if (geocoder)
		{
		geocoder.getLatLng
			(
			address,
			function(point)
				{
				if (!point) {alert(address + " not found");}
				else { map.setCenter(point, 12); }
				}
			);
		}
	}
