var baseIcon = new GIcon();
baseIcon.shadow = "/template_images/map/shadow.png";
baseIcon.iconSize = new GSize(16, 27);
baseIcon.shadowSize = new GSize(30, 27);
baseIcon.iconAnchor = new GPoint(8, 27);
baseIcon.infoWindowAnchor = new GPoint(8, 1);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var map = new GMap(document.getElementById("map_area"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

function zoomOut() {
	map.closeInfoWindow();
	loadMap();
}

function loadMap() {
	map.centerAndZoom(new GPoint( -76.618383,39.316381), 6);
}
loadMap();

var carIcon = "";
var panel = document.getElementById("map_list");

var branchLen;
var points;
var markers;
var infoHtmls;
var html = "";

// Open the info box for the specified marker.
function myOpener(i) {
	map.centerAndZoom(points[i], 4);
	markers[i].openInfoWindowHtml(infoHtmls[i]);
	/* don't throw up progress indicator */
	showProgressEvent = false;
}

// This returns a function closure that calls myOpener() with the specified arg.
// These shenanigans are necessary because the API left out client-data.
function makeOpenerCaller(i) {
	return function() { myOpener(i); };
}

// variables needed to track which site to zoom in on.
//var focusOnLocation = getQueryVariable('loc');
var focusOnLocation = focusOnThis;
var focusOn = -1;

var request = GXmlHttp.create();
request.open("GET", "branches_xml.aspx", true);
request.onreadystatechange = function() {
	if (request.readyState == 4) {
		var xmlDoc = request.responseXML;
		var branch = xmlDoc.getElementsByTagName("Branch");
		branchCount = branch.length;
		points    = new Array(branchCount);
		markers   = new Array(branchCount);
		infoHtmls = new Array(branchCount);
		for (var i = 0; i < branchCount; ++i) {
			//var name = loc[i].data; //works in IE but not Firefox
			//var name = branch[i].firstChild.nodeValue; //works in both IE and Firefox
			var city   = "Baltimore";
			var state = "MD";
			var name      = branch[i].getElementsByTagName("Branch_Name")[0].firstChild.nodeValue;
			var street    = branch[i].getElementsByTagName("Street_Address")[0].firstChild.nodeValue;
			var zip       = branch[i].getElementsByTagName("Zip_Code")[0].firstChild.nodeValue;
/* Broken because of missing phone number
			var phone     = branch[i].getElementsByTagName("Phone")[0].firstChild.nodeValue;
			var fax       = branch[i].getElementsByTagName("FAX")[0].firstChild.nodeValue;
*/
			var phone = "";
			if (branch[i].getElementsByTagName("Phone")[0].firstChild) {
				var phone     = branch[i].getElementsByTagName("Phone")[0].firstChild.nodeValue;
			}
			
			var email     = branch[i].getElementsByTagName("E-mail")[0].firstChild.nodeValue;
			var info_url  = branch[i].getElementsByTagName("URL")[0].firstChild.nodeValue;
			var map_coord = branch[i].getElementsByTagName("Map_Location");
			var lat = map_coord[0].getElementsByTagName("Latitude")[0].firstChild.nodeValue;
			var lng = map_coord[0].getElementsByTagName("Longitude")[0].firstChild.nodeValue;

			var letter = String.fromCharCode("A".charCodeAt(0) + i);
			var icon = new GIcon(baseIcon);
			icon.image = "/template_images/map/marker/" + letter + ".png";

			/* Grab thumbnail if there */
			var thumbhtml='';
			if (branch[i].getElementsByTagName("Thumbnail").length > 0) {
			if (branch[i].getElementsByTagName("Thumbnail")[0].getElementsByTagName("img").length > 0) {
			  var thumbnail = branch[i].getElementsByTagName("Thumbnail")[0].getElementsByTagName("img")[0].attributes;
			  thumbhtml = '<img ';
			  for (j=0;j<thumbnail.length;j++)
			  { 
			    if (thumbnail.item(j).name == 'alt' || thumbnail.item(j).name == 'src' ) {
			      thumbhtml += thumbnail.item(j).name + '="' + thumbnail.item(j).value + '" '
			    }
			  }
			  thumbhtml += ' style="border: 1px solid #ababab; width: 70px; height: 100px;"/>'
			}}

			points[i] = new GPoint(parseFloat(lng),parseFloat(lat));
			markers[i] = new GMarker(points[i],icon);
			var tmp = street + " " + zip;
			
			infoHtmls[i] = "<div style='width: 220px;'><div style='float:right;margin-top: 12px;'>" + thumbhtml + "</div><p align='left'><span style='font-size: 120%; font-weight: bold;'>" + name + "</span><br />" + street + "<br/>" + city + ", " + state + " " + zip + "<br/>" + phone + "<br><a href='mailto:" + email + "'>" + email + "</a><br><br><a href='" + info_url + "'>more info</a> | <a href='http://maps.google.com/maps?q=" + street + " " + city + " " + state + " " + zip + "'>directions</a></p></div>" ;
			
			GEvent.addListener(markers[i],'click',makeOpenerCaller(i));
			map.addOverlay(markers[i]);

			var link = "<a href=\"javascript:myOpener(" + i + ")\">";
			html += "<li>" + link + "<b>" + name + "</b></a></li>";
			if (name.toLowerCase() == focusOnLocation.toLowerCase()) { focusOn = i; } // pick this one to focus on.
		}
		panel.innerHTML = "<ul style=\"list-style: upper-alpha outside;\">" + html + "</ul>";
		if (focusOn >= 0 ) { myOpener(focusOn); } // pick this one to focus on.
	}
}
request.send(null);

// Out-of-the-box functions used above to zoom into a particular site
	function getQueryVariable(variable) {
		// parse the query string to get key/value pairs.
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			var no_percent = URLdecode(pair[1]);
			return no_percent;
			}
		}
		return ''; // if variable is not found, return blank.
	}

	function URLdecode(encoded) {
		// decode the supplied string, removing any %xx URL encoding (%20 -> ' ')
		// borrowed from http://netzreport.googlepages.com/online_tool_for_url_encoding_decoding.html
		//var encoded = document.converter.encoded.value;
		var unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
		var hexnumerals = "0123456789ABCDEFabcdef";
		var plain = "";
		var i = 0;
		while (i < encoded.length) {
			var ch = encoded.charAt(i);
			if (ch == "%") {
			// Check if percent sign is followed by two characters:
			if (i < (encoded.length - 2)) {
			// Check if these two characters are hexadecimal numerals:
			if (hexnumerals.indexOf(encoded.charAt(i+1)) != -1 && hexnumerals.indexOf(encoded.charAt(i+2)) != -1) {
				plain = plain + unescape(encoded.substr(i,3));
				i = i + 3;
			} else {
				alert("The string " + encoded.substr(i,3) + " cannot be decoded, because a percent\nsign must be followed by two hexadecimal characters.\nThe string will be put into square brackets.");
				plain = plain + "[" + encoded.substr(i,3) + "]";
				i = i + 3;
				}
			} else {
				alert("The string " + encoded.substr(i,2) + " cannot be decoded, because a percent\nsign must be followed by two hexadecimal characters.\nThe string will be put into square brackets.");
				plain = plain + "[" + encoded.substr(i,2) + "]";
				i = i + 2;
				}
			} else {
			// Check if character is an unreserved character:
				if (unreserved.indexOf(ch) != -1) {
					plain = plain + ch;
				} else {
				// alert("The character " + ch + " is a reserved or Unicode character. It\nis not allowed to be part of an URL encoded string.\nThe character will be put into square brackets.");
				// plain = plain + "[" + ch + "]";
					alert("The character " + ch + " is a reserved or Unicode character.\nIt should not be part of an URL encoded string.");
					plain = plain + ch;
				}
				i++;
			}
		}
		return plain;
	}