var map = null;
var geocoder = null;
var optionsXML = null;
var timer = null;
var mgr, newMarker;
var loadedFlag = false;
function loadMap(pageRoot) {
	var mapPoint = new GLatLng (43.670178, -79.38706);
  	if (GBrowserIsCompatible()) {
		listHTML = "";
		specificFlag = 0;
		matchBuildings = new Array();
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(mapPoint, 8, G_HYBRID_MAP);
		mgr = new GMarkerManager (map, {trackMarkers:true});
		document.getElementById("google-maps-form-div").style.display = "block";
		if (!loadedFlag) {
			timer = setTimeout ("retrieveBuildings('" + pageRoot + "');", 10);
			loadedFlag = true;
		}
	}
}
function createMarkerOld (fullDescription, certifications, pageRoot, iconImage, iconWidth, iconHeight, latitude, longitude) {
//	var infoTabs = [new GInfoWindowTab("Description", fullDescription), new GInfoWindowTab("Certifications", certifications)];
//	GEvent.addListener(marker, "click", function() {
//		marker.openInfoWindowTabsHtml(infoTabs);
//	});
//				if (i == 0) {
//  			 		marker.openInfoWindowTabsHtml(infoTabs);
//				}
	return marker;
}
function createMarkerNew (pageRoot, latitude, longitude, iconName, iconWidth, iconHeight, basicInfo, fullDescription) {

	var point = new GLatLng (latitude, longitude);
	var iconImage = pageRoot + "icons/" + iconName;
	var icon = new GIcon();
	icon.image = iconImage;
	icon.iconSize = new GSize(iconWidth, iconHeight);
	icon.iconAnchor = new GPoint(7, 7);
	icon.infoWindowAnchor = new GPoint(5, 1);
	var marker = new GMarker (point, icon);
	if (basicInfo != "" && fullDescription != "") {
		var infoTabs = [new GInfoWindowTab("Details", basicInfo), new GInfoWindowTab("Description", fullDescription)];
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml(infoTabs);
		});
		if (specificFlag == 1) {
			map.addOverlay(marker);
			GEvent.trigger(marker, "click");
			map.setCenter (new GLatLng (latitude, longitude), 15);
		}
	}
	return marker;
}
function generateBuildingMarkers(pageRoot) {
	var name, address, description, building, leedCertified, fullDescription, basicInfo, certifications, goGreenCertified, goGreenPlusCertified, icon, iconWidth, iconHeight, latitude, longitude, buildingId, shortDescription, certificationFields, linkFields, AnchorTextFields, URL, Anchor, ffDetect, certsListPlain, validFlag, curCert, curCertPlain, certId;
	var batch = [];
	var nameFields = optionsXML.getElementsByTagName('Name');
	var addressFields = optionsXML.getElementsByTagName('Address');
	var descriptionFields = optionsXML.getElementsByTagName('Description');
	var buildingFields = optionsXML.getElementsByTagName('Building_Type');
	var certificationsFields = optionsXML.getElementsByTagName('Certifications');
	var iconFields = optionsXML.getElementsByTagName('Icon');
	var iconWidthFields = optionsXML.getElementsByTagName('Icon_Width');
	var iconHeightFields = optionsXML.getElementsByTagName('Icon_Height');
	var latitudeFields = optionsXML.getElementsByTagName('Latitude');
	var longitudeFields = optionsXML.getElementsByTagName('Longitude');
	var buildingIdFields = optionsXML.getElementsByTagName('Building_ID');
	var shortDescriptionFields = optionsXML.getElementsByTagName('Short_Description');
	optionsXML.getElementsByTagName('LEED_Certified');
	var addressLength = addressFields.length;
	var detailTab, buildingLink;
	var marker = null;
	var infoTabs = null;
	if (addressLength == 0) {
		alert ("We're sorry.  There are no buildings that meet your criteria.  Please try again.");	
	} else {
		for (var i = 0; i < addressLength; i++) {
			marker = null;
			name = nameFields[i].firstChild.data;
			address = addressFields[i].firstChild.data;
			address = address.replace(/\r|\n|\r\n/g, "<br />");
			description = descriptionFields[i].firstChild.data;
			description = description.replace(/\r|\n|\r\n/g, "<br />");
			building = buildingFields[i].firstChild.data;
			shortDescription = shortDescriptionFields[i].firstChild.data;
			latitude = parseFloat (latitudeFields[i].firstChild.data);
			longitude = parseFloat (longitudeFields[i].firstChild.data);
			if (specificFlag == 1) {
				specificLat = latitude;
				specificLng = longitude;
			}
			buildingId = parseFloat (buildingIdFields[i].firstChild.data);
			buildingLink = "<p><a href=\"" + pageRoot + "building-details.asp?BUI=" + buildingId + "\">More Information</a></p>";
			icon = iconFields[i].firstChild.data;
			iconWidth = iconWidthFields[i].firstChild.data;
			iconHeight = iconHeightFields[i].firstChild.data;
			certificationFields = certificationsFields[i].childNodes;
			certifications = "<ul class=\"certifications\">";
			certsListPlain = "";
			var certFieldLength = certificationFields.length;
			ffDetect = false;
			for (var j = 0; j < certFieldLength; j++) {
				if (certificationFields[j].nodeName == "#text") {
					ffDetect = true;
					break;
				}
			}
			for (var j = 0; j < certFieldLength; j++) {
				validFlag = false;
				if (!ffDetect) {
					curCert = certificationFields[j].childNodes[0].text;
					URL = certificationFields[j].childNodes[1].text;
					Anchor = certificationFields[j].childNodes[2].text;
					validFlag = true;
				} else if (certificationFields[j].nodeName == "Certification_Info") {
					curCert =  certificationFields[j].childNodes[1].firstChild.data;
					URL = certificationFields[j].childNodes[3].firstChild.data;
					Anchor = certificationFields[j].childNodes[5].firstChild.data;
					validFlag = true;
				}
				if (validFlag) {
					certifications += "<li>";
					certsListPlain += "<li><span>" + curCert + "</span></li>\n";
					if (Anchor == '' || Anchor == 'undefined') {
						Anchor = URL;
					}
					if (URL != '' && URL != 'undefined') {
						certId = curCert.toLowerCase();
						certId = certId.replace (" ", "-");
						certifications += '<a href="' + pageRoot + '\/program-overview.asp#' + certId + '\">' + curCert + "</a>"
					}
					certifications += "</li>\n";
				}
			}
			certifications += "</ul>";
			certsListPlain = "<ul class=\"plain-certs-list\">" + certsListPlain + "</ul>";
			detailTab = "<p>" + address + "</p>\n" + certifications;
			basicInfo = "<h2><a href=\"" + pageRoot + "building-details.asp?BUI=" + buildingId + "\">" + name + "</a></h2>\n" + detailTab + "\n";
//			basicInfo += buildingLink;
			basicInfo = "<div style=\"max-width:  300px;  height:  100px;  overflow-y:  visible;\">" + basicInfo + "</div>\n";
			fullDescription = "<div style=\"max-width:  300px\;  height:  100px;  overflow-y:  visible;\"><h2>" + name + " Description</h2>\n<p>" + shortDescription + "</p>\n";
//			fullDescription += buildingLink;
			fullDescription += "</div>\n";
//			var newMarker = createMarker (fullDescription, certifications, pageRoot, icon, iconWidth, iconHeight, latitude, longitude);
//			newMarker = createMarker (latitude, longitude);
			marker = createMarkerNew (pageRoot, latitude, longitude, icon, iconWidth, iconHeight, basicInfo, fullDescription);
			batch.push (marker);
			matchBuildings[i] = "<div><a href=\"javascript:retrievePoint('" + pageRoot + "', " + buildingId + ");\">" + name + "</a>\n"
			matchBuildings[i] += "<br />" + address + "</div>\n" + certsListPlain;
	   	}
   	}
	return batch;
}
function createSingleMarker (pageRoot) {
	var name, address, description, building, leedCertified, fullDescription, certifications, goGreenCertified, goGreenPlusCertified, icon, iconWidth, iconHeight, latitude, longitude, buildingId, shortDescription, certificationFields, linkFields, AnchorTextFields, URL, Anchor, ffDetect, validFlag, certId;
	var nameFields = optionsXML.getElementsByTagName('Name');
	var addressFields = optionsXML.getElementsByTagName('Address');
	var descriptionFields = optionsXML.getElementsByTagName('Description');
	var buildingFields = optionsXML.getElementsByTagName('Building_Type');
	var certificationsFields = optionsXML.getElementsByTagName('Certifications');
	var iconFields = optionsXML.getElementsByTagName('Icon');
	var iconWidthFields = optionsXML.getElementsByTagName('Icon_Width');
	var iconHeightFields = optionsXML.getElementsByTagName('Icon_Height');
	var latitudeFields = optionsXML.getElementsByTagName('Latitude');
	var longitudeFields = optionsXML.getElementsByTagName('Longitude');
	var buildingIdFields = optionsXML.getElementsByTagName('Building_ID');
	var shortDescriptionFields = optionsXML.getElementsByTagName('Short_Description');
	optionsXML.getElementsByTagName('LEED_Certified');
	var addressLength = addressFields.length;
	var detailTab, buildingLink;
	var marker = null;
	var infoTabs = null;
	if (addressLength == 0) {
		alert ("We're sorry.  There are no buildings that meet your criteria.  Please try again.");	
	} else {
		for (var i = 0; i < addressLength; i++) {
			marker = null;
			name = nameFields[i].firstChild.data;
			address = addressFields[i].firstChild.data;
			address = address.replace(/\r|\n|\r\n/g, "<br />");
			description = descriptionFields[i].firstChild.data;
			description = description.replace(/\r|\n|\r\n/g, "<br />");
			building = buildingFields[i].firstChild.data;
			shortDescription = shortDescriptionFields[i].firstChild.data;
			latitude = parseFloat (latitudeFields[i].firstChild.data);
			longitude = parseFloat (longitudeFields[i].firstChild.data);
			if (specificFlag == 1) {
				specificLat = latitude;
				specificLng = longitude;
			}
			buildingId = parseFloat (buildingIdFields[i].firstChild.data);
			buildingLink = "<p><a href=\"" + pageRoot + "building-details.asp?BUI=" + buildingId + "\">More Information</a></p>";
			icon = iconFields[i].firstChild.data;
			iconWidth = iconWidthFields[i].firstChild.data;
			iconHeight = iconHeightFields[i].firstChild.data;
			certificationFields = certificationsFields[i].childNodes;
			certifications = "<ul class=\"certifications\">";
			certsListPlain = "";
			var certFieldLength = certificationFields.length;
			ffDetect = false;
			for (var j = 0; j < certFieldLength; j++) {
				if (certificationFields[j].nodeName == "#text") {
					ffDetect = true;
					break;
				}
			}
			for (var j = 0; j < certFieldLength; j++) {
				validFlag = false;
				if (!ffDetect) {
					curCert = certificationFields[j].childNodes[0].text;
					URL = certificationFields[j].childNodes[1].text;
					Anchor = certificationFields[j].childNodes[2].text;
					validFlag = true;
				} else if (certificationFields[j].nodeName == "Certification_Info") {
					curCert =  certificationFields[j].childNodes[1].firstChild.data;
					URL = certificationFields[j].childNodes[3].firstChild.data;
					Anchor = certificationFields[j].childNodes[5].firstChild.data;
					validFlag = true;
				}
				if (validFlag) {
					certifications += "<li>";
					certsListPlain += "<li><span>" + curCert + "</span></li>\n";
					if (Anchor == '' || Anchor == 'undefined') {
						Anchor = URL;
					}
					if (URL != '' && URL != 'undefined') {
						certId = curCert.toLowerCase();
						certId = certId.replace (" ", "-");
						certifications += '<a href="' + pageRoot + 'program-overview.asp#' + certId + '\">' + curCert + "</a>"
					}
					certifications += "</li>\n";
				}
			}
			certifications += "</ul>";
			certsListPlain = "<ul class=\"plain-certs-list\">" + certsListPlain + "</ul>";
			detailTab = "<p>" + address + "</p>\n" + certifications;
			basicInfo = "<h2><a href=\"" + pageRoot + "building-details.asp?BUI=" + buildingId + "\">" + name + "</a></h2>\n" + detailTab + "\n";
			basicInfo += buildingLink;
			basicInfo = "<div style=\"max-width:  300px;  height:  100px;  overflow-y:  visible;\">" + basicInfo + "</div>\n";
			fullDescription = "<div style=\"max-width:  300px\;  height:  100px;  overflow-y:  visible;\"><h2>" + name + " Description</h2>\n<p>" + shortDescription + "</p>\n";
			fullDescription += buildingLink;
			fullDescription += "</div>\n";
//			var newMarker = createMarker (fullDescription, certifications, pageRoot, icon, iconWidth, iconHeight, latitude, longitude);
//			newMarker = createMarker (latitude, longitude);
			marker = createMarkerNew (pageRoot, latitude, longitude, icon, iconWidth, iconHeight, basicInfo, fullDescription);
	   	}
   	}
}
function generateMarkers (pageRoot) {
	var buildings = generateBuildingMarkers(pageRoot);
	if (specificFlag == 0) {
		mgr.addMarkers(buildings, 8);
		mgr.refresh();
		listHTML = "<ul>\n";
		for (var i = 0; i < matchBuildings.length; i++) {
			listHTML += "<li>" + matchBuildings[i] + "</li>\n";	
		}
		listHTML += "</ul>\n";
		document.getElementById("buildings-list").innerHTML = listHTML;
	} else {
		createSingleMarker(pageRoot);
	}
	optionsText = null;
}
function gatherResponseText (pageRoot) {
	optionsText = xmlHttp.responseText;
	if (optionsText != '') {
   		optionsXML = xmlHttp.responseXML.documentElement;
		generateMarkers(pageRoot);
	} else {
		var responseTimer = setTimeout ("gatherResponseText('" + pageRoot + "')", 10);
	}
}
function retrieveBuildings (pageRoot, queryString) {
  
  try {    
  	// Firefox, Opera 8.0+, Safari    
	xmlHttp=new XMLHttpRequest(); 
  } catch (e) {    
	  	// Internet Explorer
		try {      
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");     
		} catch (e) {      
		  	try	{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {       
			 return false;        
			}      
		}   
	}  
	xmlHttp.onreadystatechange=function() {
   		if(xmlHttp.readyState==4)
       	{
			gatherResponseText(pageRoot);
			clearTimeout (timer);
			timer = null;
			return false;
	   	}
	}
	if (pageRoot != undefined && pageRoot != '' && pageRoot != "undefined") {
		var url = pageRoot + "AJAX-scripts/retrieve-buildings.asp";
		if (queryString != '' && queryString != "undefined" && queryString != undefined) {
			url += "?" + queryString;
		}
	   	xmlHttp.open("GET", url, true);
	   	xmlHttp.send(null); 
	}
	return false;
}
function concatString (curString, addOnString) {
	if (curString != '' && curString != undefined) {
		curString += "&"
	} else {
		curString = "";
	}
	curString += addOnString;
	return curString;
}
function createNewMap() {
	mapPoint = map.getCenter();
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(mapPoint, 8, G_HYBRID_MAP);
	mgr = new GMarkerManager (map, {trackMarkers:true});
	map.setZoom (8);
}
function defaultMap () {
	document.getElementById("buildings-list").innerHTML = "Loading...";
	createNewMap();
	specificFlag = 0;
	listHTML = "";
	matchBuildings = new Array();
}
function filterBuildings (pageRoot) {
	defaultMap();
	var theForm = document.getElementById("filterBuildingsForm");
	var buildingType = "";
	var certifications = "";
//	var buildingTypeField = theForm.Building_Type;
//	for (var i = 0; i < buildingTypeField.length; i++) {
//		if (buildingTypeField[i].checked) {
//			if (buildingType != "" && buildingType != "undefined") {
//				buildingType += ", ";
//			}
//			buildingType += "'" + buildingTypeField[i].value + "'";
//		}
//	}
	var certificationsField = theForm.Certification;
	for (var i = 0; i < certificationsField.length; i++) {
		if (certificationsField[i].checked) {
			if (certifications != "" && certifications != "undefined") {
				certifications += ", ";
			}
			certifications += certificationsField[i].value;
		}
	}
	var queryString;
	if (certifications != "") {
		queryString = concatString (queryString, "certification=" + certifications);
	}
	if (buildingType != "") {
		queryString = concatString (queryString, "Building_Type=" + buildingType);
	}
	retrieveBuildings (pageRoot, queryString);
	return false;
}
function retrievePoint (pageRoot, buildingId) {
	var queryString;
	createNewMap();
	buildingId = parseFloat (buildingId);
	if (buildingId > 0) {
		queryString = "Building_ID=" + buildingId
		specificFlag = 1;
		retrieveBuildings (pageRoot, queryString);
	}
}
function selectAllChecked(theField, theForm) {
	formField = document.getElementById(theForm).elements[theField];
	for (var i = 0; i < formField.length; i++) {
		formField[i].checked = true;
	}
}
function clearAllChecked(theField, theForm) {
	formField = document.getElementById(theForm).elements[theField];
	for (var i = 0; i < formField.length; i++) {
		formField[i].checked = false;
	}
}
function resetMap(pageRoot) {
	defaultMap();
	clearAllChecked ('Certification', 'filterBuildingsForm');
	buildingId = 0;
	listHTML = "";
	retrieveBuildings (pageRoot);
	return false;
}
function detailMap(pageRoot, latitude, longitude) {
  	if (GBrowserIsCompatible()) {
		specificFlag = 1;
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
		var point = new GLatLng (latitude, longitude);
        map.setCenter(point, 15, G_HYBRID_MAP);
		var iconImage = pageRoot + "icons/sbc.png";
		var icon = new GIcon();
		icon.image = iconImage;
		icon.iconSize = new GSize(24, 24);
		icon.iconAnchor = new GPoint(12, 12);
		icon.infoWindowAnchor = new GPoint(5, 1);
		var marker = new GMarker (point, icon);
		map.addOverlay (marker);
	}
}
var listHTML, matchBuildings, specificFlag, specificLat, specificLng, optionsText, mapPoint;