var stn;
var state;
var lat;
var lon;
function showLU(station,sname)
{
	// when called we should 
	body = document.getElementsByTagName('body')[0]
	if (document.getElementById("l_u_d")) { return } // prevents making multiple boxes
	element = document.createElement('div');
	element.setAttribute('id','l_u_d');
	element.setAttribute('style','width:500px;height:250px;position:absolute;top:110px;left:300px;display:block;'+
			'background-color:#FFFFFF;border:4px solid #CCCCCC;font-size:13px;padding:3px;overflow:auto');
	// NOW WE WANT TO CREATE THE THING YOU GRAB ONTO TO DRAG THE BOX!
	title = document.createElement("div");
	title.setAttribute('id','l_u_d_d');
	title.setAttribute('style','width:450px;position:relative;top:0;left:0;z-index:0;background-color:#002c94;padding:2px;color:#FFFFFF;font-family:helvetica,arial,sans-serif;');
	title.setAttribute('onmousedown',"drag.start()");
	title.innerHTML = "Land cover data for "+sname.bold()+" ("+station+")";
	element.appendChild(title);
	// create the div for the loaded contents!
	cont_div = document.createElement('div');
	cont_div.setAttribute('id','luinterior');
	cont_div.setAttribute('style','overflow:auto;width:499px;height:200px;');
	cont_div.innerHTML = "<center><img src='/images/mesowest_static/loading.gif' /></center>";
	element.appendChild(cont_div)
	// now append the rest of the elements
	element.innerHTML += "<div style='position:absolute;right:0;top:0;padding:3px;font-size:10px'><b><a href='javascript:closeDiv(\"l_u_d\")'>CLOSE</a></b></div>";

	body.appendChild(element);
	// now we want to make the ajax request to get the loaded material from the cgi bin...
	stn = station;
	request("/cgi-bin/droman/land_use.cgi","s="+station,writeVals);
}
function writeVals(data)
{
	// the data is the categorical overview of the land use, 
	data = data.split("!@#");
        data2 = data[1].split(",");
	data1 = data[0].split("\n");
	state = data2[0];
	lat = data2[1];
	lon = data2[2];
	out = "<table style='font-size:13px;width:100%'><tr><td valign='top' width='180px'><table style='font-size:13px;'><tr><th>Class</th><th width='40px;'>Percent of area</th></tr>";
	for (l in data1)
	{
		d = data1[l].split(":");
		if (d[1]=="0.00" || !data1[l]) continue;
		// we want to round d[1], so lets do a little maths.
		d[1] = Math.round(d[1]);
		out += "<tr><td><img src='/images/land_use/"+d[0]+"_color.gif' width='10' height='10'> "+
			"<a href='javascript:describe("+d[0]+")' id='lk_"+d[0]+"'>"+trans_code[d[0]]+"</a></td><td><center>"+d[1]+"%</center></td></tr>";
	}
	out += "</table><i>Percent computed based on 1km x 1km box around station</i></td><td width='160' valign='top'><center>"+
	"<table><tr><td width='33%' bgcolor='#CCCCCC'><center><a href='javascript:mapSwap(\"lc\")'>L/C</a></center></td>"+
	"<td width='33%' bgcolor='#CCCCCC'> <a href='javascript:mapSwap(\"sat\")'>Sattelite</a></td>"+
	"<td width='33%' bgcolor='#CCCCCC'> <a href='javascript:mapSwap(\"ter\")'>Terrain</a></td></tr></table>"+
	"<img src='/images/land_use/stations/"+data2[0]+"/"+stn+"_3x3.gif' id='map_t'/>"+
	"<br /><div id='img_desc'> <i>Grid image with 1km x 1km box and an 'X' to mark station location</i></div></center></td></tr></table>";
	document.getElementById('luinterior').innerHTML = out;
}

function mapSwap(i)
{
	// ths function will switch the image
	if (i=='lc') {
		document.getElementById('map_t').src = "/images/land_use/stations/"+state+"/"+stn+"_3x3.gif";
		document.getElementById('img_desc').innerHTML = "<i>Grid image with 1km x 1km box and an 'X' to mark station location</i>";
	} else if (i == 'sat')
	{
		document.getElementById('map_t').src = "http://maps.google.com/maps/api/staticmap?center="+lat+","+lon+
			"&zoom=14&size=150x150&maptype=satellite&sensor=false&markers=color:FF00000|size:mid|"+lat+","+lon;
		document.getElementById('img_desc').innerHTML = "";

	} else
	{
		document.getElementById('map_t').src = "http://maps.google.com/maps/api/staticmap?center="+lat+","+lon+
			"&zoom=13&size=150x150&maptype=terrain&sensor=false&markers=color:FF00000|size:mid|"+lat+","+lon;
		document.getElementById('img_desc').innerHTML = "";
	}
}



function closeDiv(id)
{
	//simply delete the element
	box = document.getElementById(id);
	box.parentNode.removeChild(box);
}

var drag = {
	dragging:false,
	off_x: false,
	start: function()
	{
		drag.dragging = true;
		// create the listener for the mousemove
		if (!document.all) {
			document.captureEvents(Event.MOUSEMOVE);
			document.captureEvents(Event.MOUSEUP);	
		}
		document.onmousemove = drag.drag;
		document.onmouseup = drag.stop;
		document.getElementById('l_u_d').style.cursor = "move";
		//document.getElementById('img_desc').innerHTML = "dragging?";
		
	},
	drag: function(e)
	{
		//get mouse position
		if (!drag.dragging) return false;
		if (e.clientX)
		{
			//ie
			x = e.clientX + document.body.scrollLeft;
			y = e.clientY + document.body.scrollTop;
		} else 
		{
			x = e.pageX;
			y = e.pageY;
		//	document.getElementById('img_desc').innerHTML  = x+","+y;
		}
		style = document.getElementById("l_u_d").style;
		// calculate pixel offset, only once, so that we can figure how far off to move the box
		if (!drag.off_x)
		{
			drag.off_x = x - 1 * style.left.replace("px","");
			drag.off_y = y - 1 * style.top.replace("px","");
		}
		style.top = y - drag.off_y + "px";
		style.left = x - drag.off_x + "px";
		return false;
	},
	stop: function()
	{
		document.onmousemove = void(0);
		document.onmouseup = void(0);
		drag.dragging = false;
		drag.off_x = false;
		document.getElementById('l_u_d').style.cursor = "auto";
	}
};

function describe(id)
{
	obj = document.getElementById("lk_"+id);
	pos = findPos(obj);
	// lets adjust for some offset
	pos[0] += 35;
	pos[1] += 20;
	if (document.getElementById("l_u_i")) {closeDiv("l_u_i"); } // prevents making multiple boxes
	var d = {
	1 : "No data value, Alaska zones only",
	11: "Open Water - All areas of open water, generally with less than 25% cover or vegetation or soil",
	12: "Perennial Ice/Snow - All areas characterized by a perennial cover of ice and/or snow, generally greater than 25% of total cover.",
	21: "Developed, Open Space - Includes areas with a mixture of some constructed materials, but mostly vegetation in the form of lawn grasses.  Impervious surfaces account for less than 20 percent of total cover.  These areas most commonly include large-lot single-family housing units, parks, golf courses, and vegetation planted in developed settings for recreation, erosion control, or aesthetic purposes.",
	22: "Developed, Low Intensity -Includes areas with a mixture of constructed materials and vegetation.  Impervious surfaces account for 20-49 percent of total cover.  These areas most commonly include single-family housing units.",
	23: "Developed, Medium Intensity - Includes areas with a mixture of constructed materials and vegetation. Impervious surfaces account for 50-79 percent of the total cover.  These areas most commonly include single-family housing units.",
	24: "Developed, High Intensity - Includes highly developed areas where people reside or work in high numbers. Examples include apartment complexes, row houses and commercial/industrial.  Impervious surfaces account for 80 to100 percent of the total cover.",
	31: "Barren Land (Rock/Sand/Clay) - Barren areas of bedrock, desert pavement, scarps, talus, slides, volcanic material, glacial debris, sand dunes, strip mines, gravel pits and other accumulations of earthen material. Generally, vegetation accounts for less than 15% of total cover.",
	32: "Unconsolidated Shore* - Unconsolidated material such as silt, sand, or gravel that is subject to inundation and redistribution due to the action of water. Characterized by substrates lacking vegetation except for pioneering plants that become established during brief periods when growing conditions are favorable. Erosion and deposition by waves and currents produce a number of landforms representing this class.",
	41: "Deciduous Forest  - Areas dominated by trees generally greater than 5 meters tall, and greater than 20% of total vegetation cover. More than 75 percent of the tree species shed foliage simultaneously in response to seasonal change.",
	42: "Evergreen Forest - Areas dominated by trees generally greater than 5 meters tall, and greater than 20% of total vegetation cover. More than 75 percent of the tree species maintain their leaves all year. Canopy is never without green foliage.",
	43: "Mixed Forest - Areas dominated by trees generally greater than 5 meters tall, and greater than 20% of total vegetation cover. Neither deciduous nor evergreen species are greater than 75 percent of total tree cover.",
	51: "Dwarf Scrub - Alaska only areas dominated by shrubs less than 20 centimeters tall with shrub canopy typically greater than 20% of total vegetation. This type is often co-associated with grasses, sedges, herbs, and non-vascular vegetation.",
	52: "Shrub/Scrub - Areas dominated by shrubs; less than 5 meters tall with shrub canopy typically greater than 20% of total vegetation. This class includes true shrubs, young trees in an early successional stage or trees stunted from environmental conditions.",
	71: "Grassland/Herbaceous - Areas dominated by grammanoid or herbaceous vegetation, generally greater than 80% of total vegetation.  These areas are not subject to intensive management such as tilling, but can be utilized for grazing.",
	72: "Sedge/Herbaceous - Alaska only areas dominated by sedges and forbs, generally greater than 80% of total vegetation. This type can occur with significant other grasses or other grass like plants, and includes sedge tundra, and sedge tussock tundra.",
	73: "Lichens - Alaska only areas dominated by fruticose or foliose lichens generally greater than 80% of total vegetation.",
	74: "Moss- Alaska only areas dominated by mosses, generally greater than 80% of total vegetation.",
	81: "Pasture/Hay  - Areas of grasses, legumes, or grass-legume mixtures planted for livestock grazing or the production of seed or hay crops, typically on a perennial cycle. Pasture/hay vegetation accounts for greater than 20 percent of total vegetation.",
	82: "Cultivated Crops - Areas used for the production of annual crops, such as corn, soybeans, vegetables, tobacco, and cotton, and also perennial woody crops such as orchards and vineyards. Crop vegetation accounts for greater than 20 percent of total vegetation. This class also includes all land being actively tilled.",
	90: "Woody Wetlands - Areas where forest or shrub land vegetation accounts for greater than 20 percent of vegetative cover and the soil or substrate is periodically saturated with or covered with water.",
	91: "Palustrine Forested Wetland* -Includes all tidal and non-tidal wetlands dominated by woody vegetation greater than or equal to 5 meters in height and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is below 0.5 percent. Total vegetation coverage is greater than 20 percent.",
	92: "Palustrine Scrub/Shrub Wetland* - Includes all tidal and non-tidal wetlands dominated by woody vegetation less than 5 meters in height, and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is below 0.5 percent. Total vegetation coverage is greater than 20 percent. The species present could be true shrubs, young trees and shrubs or trees that are small or stunted due to environmental conditions.Palustrine Scrub/Shrub Wetland* - Includes all tidal and non-tidal wetlands dominated by woody vegetation less than 5 meters in height, and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is below 0.5 percent. Total vegetation coverage is greater than 20 percent. The species present could be true shrubs, young trees and shrubs or trees that are small or stunted due to environmental conditions.",
	93: "Estuarine Forested Wetland* - Includes all tidal wetlands dominated by woody vegetation greater than or equal to 5 meters in height, and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is equal to or greater than 0.5 percent. Total vegetation coverage is greater than 20 percent.",
	94: "Estuarine Scrub/Shrub Wetland* - Includes all tidal wetlands dominated by woody vegetation less than 5 meters in height, and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is equal to or greater than 0.5 percent. Total vegetation coverage is greater than 20 percent.",
	95: "Emergent Herbaceous Wetlands - Areas where perennial herbaceous vegetation accounts for greater than 80 percent of vegetative cover and the soil or substrate is periodically saturated with or covered with water.",
	96: "Palustrine Emergent Wetland (Persistent)* - Includes all tidal and non-tidal wetlands dominated by persistent emergent vascular plants, emergent mosses or lichens, and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is below 0.5 percent. Plants generally remain standing until the next growing season.",
	97: "Estuarine Emergent Wetland* - Includes all tidal wetlands dominated by erect, rooted, herbaceous hydrophytes (excluding mosses and lichens) and all such wetlands that occur in tidal areas in which salinity due to ocean-derived salts is equal to or greater than 0.5 percent and that are present for most of the growing season in most years. Perennial plants usually dominate these wetlands.",
	98: "Palustrine Aquatic Bed* - The Palustrine Aquatic Bed class includes tidal and nontidal wetlands and deepwater habitats in which salinity due to ocean-derived salts is below 0.5 percent and which are dominated by plants that grow and form a continuous cover principally on or at the surface of the water. These include algal mats, detached floating mats, and rooted vascular plant assemblages.",
	99: "Estuarine Aquatic Bed* - Includes tidal wetlands and deepwater habitats in which salinity due to ocean-derived salts is equal to or greater than 0.5 percent and which are dominated by plants that grow and form a continuous cover principally on or at the surface of the water. These include algal mats, kelp beds, and rooted vascular plant assemblages."
	};
	body = document.getElementsByTagName('body')[0]
	element = document.createElement('div');
	element.setAttribute('id','l_u_i');
	element.setAttribute('style','width:300px;height:100px;position:absolute;top:'+pos[1]+'px;left:'+pos[0]+'px;display:block;'+
			'background-color:#FFFFFF;border:4px solid #CCCCCC;font-size:13px;padding:3px;overflow:auto;text-align:left;');
	element.innerHTML = "<div style='float:right;padding:3px;font-size:10px'><b><a href='javascript:closeDiv(\"l_u_i\")'>CLOSE</a></b></div>"+
		d[id]+"<br /><br />Source: USGS 2001 NLCD http://www.mrlc.gov"+
		"<div style='float:right;padding:3px;font-size:10px'><b><a href='javascript:closeDiv(\"l_u_i\")'>CLOSE</a></b></div>";
	body.appendChild(element);
	// let us set an onclick attribute that will close the windows should they click outside it!
	//body.setAttribute("onclick","iClicked('l_u_i')");
	document.onmousedown = iClicked;

	//alert(d[id]+"\n\nSource: USGS 2001 NLCD http://www.mrlc.gov");
}
function iClicked(e)
{
	// determine if they clicked outside the object, and if so, then remove that object
	if (e.target.id != "l_u_i")
	{
		closeDiv('l_u_i');
		document.onmousedown = false;
	}
	
}
function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent)
	}
	return [curleft,curtop];
}
var trans_code = {
	"11":"Open Water",
	"12":"Perennial Ice/Snow",
	"21":"Developed, Open Space",
	"22":"Developed, Low Intensity",
	"23":"Developed, Med Intensity",
	"24":"Developed, High Intensity",
	"31":"Barren Land",
	"32":"Unconsolidated Shore*",
	"41":"Deciduous Forest",
	"42":"Evergreen Forest",
	"43":"Mixed Forest",
	"51":"Dwarf Shrub",
	"52":"Shrub/Scrub",
	"71":"Grassland/Herbaceous",
	"72":"Sedge/Herbaceous",
	"73":"Lichens",
	"74":"Moss",
	"81":"Pasture/Hay",
	"82":"Cultivated Crops",
	"90":"Woody Wetlands",
	"91":"Palustrine Forested Wetland*",
	"92":"Palustrine Scrub/Shrub Wetland*",
	"93":"Estuarine Forested Wetland*",
	"94":"Estuarine Scrub/Shrub Wetland*",
	"95":"Emergent Herbaceous Wetlands"
	// there is 96-99 of random wetlands that we can update if needed
}

function request(url,post,dumpFuncName)
{
	// this will make a more formal request using the readyStates to hopefully operate better with basic requests
	// when provided with the apropriate output function

	if (window.XMLHttpRequest)
	{	var http = new XMLHttpRequest(); }
	else
	{	var http = new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	http.open("POST",url,true);
	http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length",post.length);
	http.setRequestHeader("Connection","close");
	http.onreadystatechange = function() {
		if (this.readyState == 4)
		{
			dumpFuncName(this.responseText);
		}
	};
	http.send(post);
}
/* copied from a variety of sources ... */
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}


