//<![CDATA[
		   
//***************
// TAB FUNCTIONS
//***************

//UPDATE TAB CONTENT
function tabSelect(newtab) 
{
	var aTabSelectValue = document.getElementById("tabSelectValue").value;
	document.getElementById(aTabSelectValue).id=newtab;
	document.getElementById("tabSelectValue").value=newtab;
	document.getElementById("tabContent").innerHTML = frames["tabContentHTML"].document.getElementById(newtab).innerHTML
}


//***************
// FORM FUNCTIONS
//***************
//UPDATE SELECT GEOGRAPHY CONTENT IN COMMUNITY PROFILES TAB

function addindicatorlayer()
{
	var aSelectedIndicator = document.getElementById("selectedindicator").value;
	//alert(aSelectedIndicator);
	if (aSelectedIndicator != "none" && aSelectedIndicator != "zoomintoactivate")
	{
		map.clearOverlays();
		aCenterPoint = map.getCenter();
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var minX = southWest.lng();
		var minY = southWest.lat();
		var maxX = northEast.lng();
		var maxY = northEast.lat();	
		//alert(minX+","+minY+","+maxX+","+maxY);
		var y = aCenterPoint.lat();
		var x = aCenterPoint.lng();
		
		var kml = new GGeoXml("http://communityfootprint.justenvirons.org/php/pointkml.php?&abbv="+aSelectedIndicator+"&minX="+minX+"&minY="+minY+"&maxX="+maxX+"&maxY="+maxY);
		map.addOverlay(kml);
	}
	else
	{
		map.clearOverlays();
	}
}

function geographySelect(selecttype) 
{
	document.getElementById("selectGeographyForm").innerHTML = frames["selectGeographyContentHTML"].document.getElementById(selecttype).innerHTML;
}


//****************
//COMMUNITY EXPLORER
//****************
//CUSTOM MAP ICONS

var locateIcon = new GIcon();
locateIcon.image = "http://www.transecology.info/maps/icons/icon_pingrey.png";
locateIcon.shadow = "http://www.transecology.info/maps/icons/icon_base_shadow.png";
locateIcon.iconSize = new GSize(12, 20);
locateIcon.shadowSize = new GSize(22, 20);
locateIcon.iconAnchor = new GPoint(6, 10);
locateIcon.infoWindowAnchor = new GPoint(5, 1);

//GEOCODER
//PROCESS GEOCODE TEXT FROM INPUT LOCATION TEXT BOX

function processGeocodeText()
{
	  var GeocodeText = document.getElementById('GeocodeText').value;
	  geocoder.getLocations(GeocodeText, validateInputLocation);
}

function validateInputLocation(response) 
{
  var GeocodeText = document.getElementById('GeocodeText').value;
  document.getElementById('GeocodeText').value = "";
  this.map = map;
  if (!response || response.Status.code != 200) 
  {
    document.getElementById("LocationResults").innerHTML = "<div align='center'>Sorry. Location '" + GeocodeText + "' was not found.  Please enter a different location.</div>";
  } 
  else 
  {
    aPlace = response.Placemark[0];
	aAdministrativeArea = aPlace.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
	if (aAdministrativeArea == "CA")
	{
		if (aPlace.AddressDetails.Accuracy > 5)
		{
			//alert("accuracy >5");
			aZipCode = aPlace.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
			//document.getElementById("LocationResults").innerHTML= aPlace.address + '<br>' + 'Status: <br>' +response.Status.code + '<br><b>Postal code:</b> ' + aPlace.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
			addZipLocationToMap(aZipCode);
		}
		if (aPlace.AddressDetails.Accuracy == 5)
		{
			//alert("accuracy = 5");
			aZipCode = aPlace.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
			//document.getElementById("LocationResults").innerHTML= aPlace.address + '<br>' + 'Status: <br>' +response.Status.code + '<br><b>Postal code:</b> ' + aPlace.AddressDetails.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
			addZipLocationToMap(aZipCode);
		}
		else
		{
			point = new GLatLng(aPlace.Point.coordinates[1],
			aPlace.Point.coordinates[0]);	
			//marker = new GMarker(point, locateIcon);
			//map.addOverlay(marker);
			map.clearOverlays();
			map.setCenter(point, 13);
			document.getElementById("LocationResults").innerHTML="<div align='center'>Location was found, but not within the appropriate scale.  Try selecting a ZIP code region from list.</div>";
		}
	}
	else
	{
		document.getElementById("LocationResults").innerHTML="<div align='center'>Location is not in California.  Try selecting a ZIP code region from list.</div>";
	}
  }
}

function addZipLocationToMap(aZipCode)
{
	if (aZipCode==0)
	{
		aZipCode = document.getElementById("selectedzip").value;
	}
	var request = GXmlHttp.create();
	request.open("GET", "http://communityfootprint.justenvirons.org/php/polykml.php?type=zip&zip="+aZipCode, true);
	request.onreadystatechange = function() 
	{
		if (request.readyState != 4) return;		
		if (request.status == 200) 
		{
		  var xmlDoc = GXml.parse(request.responseText);
		  var zippolygons = xmlDoc.documentElement.getElementsByTagName("PolyBounds");
		  for (var i = 0; i < zippolygons.length; i++) 
		  {
			var minX = zippolygons[i].getAttribute("minXval");
			var maxX = zippolygons[i].getAttribute("maxXval");
			var minY = zippolygons[i].getAttribute("minYval");
			var maxY = zippolygons[i].getAttribute("maxYval");
			aSWPoint = new GLatLng(minY,minX);
			aNEPoint = new GLatLng(maxY,maxX);
		  }
		var aNewBounds = new GLatLngBounds(aSWPoint,aNEPoint);
		map.setCenter(aNewBounds.getCenter(),map.getBoundsZoomLevel(aNewBounds,map.getSize()));
		var kml = new GGeoXml("http://communityfootprint.justenvirons.org/php/polykml.php?type=zip&zip="+aZipCode);
		map.clearOverlays();
		map.addOverlay(kml);
		document.getElementById("selectedindicator").value="none";
		//document.getElementById("communityzip").innerHTML = aZipCode;
		generateprofile(aZipCode);
		}
		else 
		{
			document.getElementById("LocationResults").innerHTML = "<div align='center'>Sorry. Location was not found.  Please enter a different location.</div>";
		}
	}
	request.send(null);
}

function generateprofile(aZipCode)
{

	var sigdigits=new Array(0,0,2,2,2,2,2,2,0,2,2,2);
	var californiaindicatorsarray=new Array("36,861,531", "12,192,999", "158,118.97", "233.13", "1.99", "22.97", "71.83", "55.03", "53,973", "13.89", "37.29", "9.57");
	aProfileContent = "<div align='center'><span class = 'textconcept'>Annual GHG Emissions, ZIP Code Region "+aZipCode+"</span><br>Measured in metric tons of CO2 equivalents (mTCO2e)<br>1 metric ton = 2,204.62 lbs (1,000 kg)<br><table><tr><th><div align='left'>Indicator</div></th><th><div align='center'>GHG Emissions</div></th><th><div align='center'>Per Household</div></th><th><div align='center'>Per Capita</div></th><th><div align='center'>Per Square Mile</div></th></tr>";
	aIndicatorTable = "<div align='center'><span class = 'textconcept'>Additional Indicators, ZIP Code Region "+aZipCode+" vs. California</span><table><tr><th><div align='left'>Indicator</div></th><th><div align='center'>"+aZipCode+"</div></th><th><div align='center'>California</div></th></tr>";
	var request = GXmlHttp.create();
	request.open("GET", "http://communityfootprint.justenvirons.org/php/generateprofile.php?type=zip&zip="+aZipCode, true);
	request.onreadystatechange = function() 
	{
		if (request.readyState != 4)
		{
			document.getElementById("LocationResults").innerHTML="<div align='center'>Creating profile...Please wait.</div>";
			return;
		}

		if (request.status == 200) 
		{
		  totalghg = 0;
		  var xmlDoc = GXml.parse(request.responseText);
		  var profiles = xmlDoc.documentElement.getElementsByTagName("profile");
		  for (var i = 0; i < profiles.length; i++) 
		  {
  			var name = profiles[i].getAttribute("name");
		  }
		  var indicators = xmlDoc.documentElement.getElementsByTagName("indicator");
		  j=0;
		  for (var i = 0; i < indicators.length; i++) 
		  {
			var abbv = indicators[i].getAttribute("abbv");
			var title = indicators[i].getAttribute("title");
			var value = indicators[i].getAttribute("value");
			var valuenumber = indicators[i].getAttribute("valuenumber")*1;			
			var perhh = indicators[i].getAttribute("perhh");
			var percap = indicators[i].getAttribute("percap");
			var persqmi = indicators[i].getAttribute("persqmi");			
			if(abbv.substring(0,3)=="ghg")
			{
				totalghg = totalghg + valuenumber;	
				aProfileContent = aProfileContent+"<tr><td><div align='left'>"+title+"</div</td><td><div align='right'>"+value+"</div></td><td><div align='right'>"+perhh+"</div></td><td><div align='right'>"+percap+"</div></td><td><div align='right'>"+persqmi+"</div></td></tr>";
			}
			else
			{
				aIndicatorTable = aIndicatorTable+"<tr><td><div align='left'>"+title+"</div</td><td><div align='right'>"+addCommas(valuenumber.toFixed(sigdigits[j]))+"</div></td><td><div align='right'>"+californiaindicatorsarray[j]+"</div></td></tr>";
				j++;
			}
			if(abbv == "indtotalpop06")
			{
				totpop = valuenumber;
			}
			if(abbv == "indhouseholds06")
			{
				tothh = valuenumber;
			}
			if(abbv == "indsquaremiles06")
			{
				totsqmi = valuenumber;
			}
		  }
		  aProfileContent = aProfileContent+"<tr><th><div align='left'><em>Total</em></div></th><th><div align='right'><em>"+addCommas(totalghg.toFixed(0))+"</em></div></th><th><div align='right'><em>"+addCommas((totalghg/tothh).toFixed(1))+"</em></div></th><th><div align='right'><em>"+addCommas((totalghg/totpop).toFixed(1))+"</em></div></th><th><div align='right'><em>"+addCommas((totalghg/totsqmi).toFixed(1))+"</em></div></th></tr>";
		  aIndicatorTable = aIndicatorTable+"</table>";
		  aProfileContent = aProfileContent+"</table><br><br><img name='GHG Emissions Performance "+aZipCode+"' src='http://communityfootprint.justenvirons.org/php/graphanother.php?zip="+aZipCode+"&totalghg="+totalghg+"'/><br><br>"+aIndicatorTable;
		  document.getElementById("LocationResults").innerHTML = aProfileContent;
		}
		else
		{
			document.getElementById("LocationResults").innerHTML="<div align='center'>Location was not found.</div>";
		}
	}
	request.send(null);
}

//LISTENER ACTIONS
function clickPointAction(point)
{
	//alert("clicked map");
	var	lat = point.y.toFixed(5);
	var lng = point.x.toFixed(5);
	//var kml = new GGeoXml("http://communityfootprint.justenvirons.org/php/polykml.php?type=point&lng="+lng+"&lat="+lat);
	//map.clearOverlays();
	//map.addOverlay(kml);
	var request = GXmlHttp.create();
	  request.open("GET", "http://communityfootprint.justenvirons.org/php/polykml.php?type=point&lng="+lng+"&lat="+lat, true);
      request.onreadystatechange = function() 
	  {
        if (request.readyState == 4) 
		{
          var xmlDoc = GXml.parse(request.responseText);
          var zippolygons = xmlDoc.documentElement.getElementsByTagName("PolyBounds");
          for (var i = 0; i < zippolygons.length; i++) 
		  {
            var minX = zippolygons[0].getAttribute("minXval");
            var maxX = zippolygons[0].getAttribute("maxXval");
            var minY = zippolygons[0].getAttribute("minYval");
            var maxY = zippolygons[0].getAttribute("maxYval");
			aSWPoint = new GLatLng(minY,minX);
			aNEPoint = new GLatLng(maxY,maxX);
		  }
		var aNewBounds = new GLatLngBounds(aSWPoint,aNEPoint);
		map.setCenter(aNewBounds.getCenter(),map.getBoundsZoomLevel(aNewBounds,map.getSize()));
        }
      }
      request.send(null);
}

//ADD KMLS
function addKMLFile(aKMLName) 
{
	map.clearOverlays();
	var kml = new GGeoXml("http://www.transecology.info/spatial/projects/"+aKMLName+".php");
	map.addOverlay(kml);
}


//POST MESSAGE
function sendMessage() 
{
	if (document.getElementById('message').value=="")
	{
	}
	else
	{
		var strMessage = "message="+encodeURI(document.getElementById('message').value);
		makeMessagePOSTRequest(strMessage); 
	}
}

function makeMessagePOSTRequest(parameters)
{
	http_request = false;
	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
			}
		}
	}
	if (!http_request) 
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = alertContentsMessagePost;
	http_request.open('POST', '../php/postmessage.php', true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}

function alertContentsMessagePost()
{
	if (http_request.readyState<4) 
	{
		document.getElementById("postMessageUpdate").innerHTML = "<span class='textbasicform'><br>Submitting message...Please wait.</span><br>";
	}
	else if (http_request.readyState == 4) 
	{
		document.getElementById("postMessageUpdate").innerHTML = "<span class='textbasicform'><br>Thanks for submitting your message to JustEnvirons.</span><br>";
		document.getElementById("message").value = "";
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//]]>