
//making the overlay layers global variables
var geoBounds, geoTrails, geoWild, geoCGs;

//used as a shortcut to get elements
function $(x) {
    return document.getElementById(x);
}
//used to add/remove layers from the map
function _KML(item)
{
if(item.checked) //turning on a layer
  {
    switch(item.id)
      {
      case "bounds":
      map.addOverlay(geoBounds);
      break;
      case "trails":
      map.addOverlay(geoTrails);
      break;
      case "wild":
      map.addOverlay(geoWild);
      break;
      case "CGs":
       map.addOverlay(geoCGs);
      break;
      }
  }
if(!item.checked) //turning off a layer
  {
    switch(item.id)
      {
      case "bounds":
      map.removeOverlay(geoBounds);
      break;
      case "trails":
      map.removeOverlay(geoTrails);
      break;
      case "wild":
      map.removeOverlay(geoWild);
      break;
      case "CGs":
      map.removeOverlay(geoCGs);
      break;
      }
  }
}
//used to turn the layers dialog 
function makeHtmlControl(content) {
    function HtmlControl(content) {
        this.content = content;
    }
    
    HtmlControl.prototype = new GControl();
    
    HtmlControl.prototype.initialize = function(map) {
        map.getContainer().appendChild(this.content);
        return this.content;
    }
    
    HtmlControl.prototype.getDefaultPosition = function() {
        return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
    }
    
    HtmlControl.prototype.printable = function() { return false; }
    
    HtmlControl.prototype.selectable = function() { return false; }

    return new HtmlControl(content);
}

var glob_height=true;
var glob_width=true;

var map=null;
function initialize(){
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.086097,-105.93946), 9);
map.setMapType(G_PHYSICAL_MAP);
map.enableContinuousZoom();
map.enableDoubleClickZoom();
map.enableScrollWheelZoom();
var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
var topRight2 = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(100,10));
map.addControl(new GMenuMapTypeControl(), topRight2);
map.addControl(new GLargeMapControl3D(), topRight);
map.addMapType(G_PHYSICAL_MAP);

//sniff for checkbox positioning


var someButton= new makeHtmlControl($('con1'));
map.addControl(someButton,new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(195, 10)));

geoBounds = new GGeoXml("kml/bounds.kmz");
geoTrails = new GGeoXml("kml/trails.kmz");
geoWild = new GGeoXml("kml/wild.kmz");
geoLakes = new GGeoXml("kml/Lakes.kmz");
geoCGs = new GGeoXml("kml/CGs.kmz");
geoRDs = new GGeoXml("kml/RDs.kmz");
geoRec = new GGeoXml("kml/Rec.kmz");
geoLaunch = new GGeoXml("kml/Launch.kmz");
////Mouse pointer
/*
 GEvent.addListener(map, 'click', function(overlay, point) {
        if (overlay) {
          map.removeOverlay(overlay);
        } else if (point) {
          alert(point);
        }
      }); */
}

//used to collapse/expand the layers dialog on the map control
function toggleg(a, b, c) 
{
    a.cancelBubble = true;
    if (document.getElementById(b).style.display == "none") 
    {document.getElementById(b).style.display = "block";} 
    else 
    {document.getElementById(b).style.display = "none";}
}

//preloads the icon images
function preloader()
{
var img=null;
//var b='';
for(i=0;i<10;i++)
{ 
img = new Image();
b=i.toString().toUpperCase;
img.src = "http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+b+b+b+".png";
img.src= "http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+b+b+".png";
}
for(i=65;i<81;i++)
{
var z=String.fromCharCode(i);
img = new Image(); 
img.src = "http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+z+z+z+".png";
img.src= "http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+z+z+".png";
}

}
//large function responsible for windwo size maintenance
function resize()
{
var browser=sniff();
var a = screensize();
var g = 0;
//test if we're losing the left panel...
if($('body'))
  {
  if(a.y<620)//the screen height is less than 600px
    {
    glob_height=false;
     if($('content')){$('content').style.height="500px";} //works
     if($('map')){$('map').style.height="500px";} //works
     if($('survey')){$('survey').style.height="500px";} //works
     if($('content2')){$('content2').style.height="500px";} //works
    }
    else //the screen height is more than 620 BUT we have to check if the horizontal task bar is present
    {
      if(a.x<900)
      {
      glob_width=false;
     
      if(browser==1||browser==3){g=156;} //FF and Opera don't take the horiz scroll into effect.
      else{g=139;}
      }
      else{g=139;glob_height=true}
      //yes we will need to sniff here
      //IE does not take the scroll bar into consideration {+1 for IE}
      if($('content')){$('content').style.height=a.y-g+"px";}
      if($('map')){$('map').style.height=a.y-g+"px";}
      if($('survey')){$('survey').style.height=a.y-g+"px";}
      if($('content2')){$('content2').style.height=a.y-g-19+"px";} //works
    }
  if(a.x<900)
    {
    glob_width=false;
    var f=900;
    $('topnavbar').style.width=f+"px";
    $('bottomnavbar').style.width=f+"px";
    if($('map')){$('map').style.width=f+"px";}
    }
    else
    {
    glob_width=true;
    $('topnavbar').style.width="100%";
    $('bottomnavbar').style.width="100%";
    if($('content')){$('content').style.width="100%";}
    if($('map')){$('map').style.width="100%";}
    }
  } 
}

//when a div dot is dropped on the map a new one is created with this function
function givebirth(_el)
{

var newdiv = document.createElement('div');
var divIdName = _el;
newdiv.setAttribute('id',divIdName);
if(_el==0||_el=="C"||_el=="M"){var vert=0;}
if(_el==1||_el=="D"||_el== "N"){var vert=30;}
if(_el==2||_el=="E"||_el=="O"){var vert=60;}
if(_el==3||_el=="F"||_el=="P"){var vert=90;}
if(_el==4||_el=="G"){var vert=120;}
if(_el==5||_el=="H"){var vert=150;}
if(_el==6||_el=="I"){var vert=180;}
if(_el==7||_el=="J"){var vert=210;}
if(_el==8||_el=="K"){var vert=240;}
if(_el==9||_el=="L"){var vert=270;}
if(_el=="A"){var vert=300;}
if(_el=="B"){var vert=330;}

//var vert=(parseInt(_el,16)+1)*30;
newdiv.style.top = vert+"px";
newdiv.style.zIndex = "110";
newdiv.style.position = "absolute";
newdiv.style.cursor = "pointer";
newdiv.innerHTML = "<img src='icn/"+_el+".png' onmouseover='this.src=\"icn/"+_el+_el+_el+".png\";' onmouseout='this.src=\"icn/"+_el+".png\";'>";
//
if(parseInt(_el)<10||_el=="A"||_el=="B"){$('drag1').appendChild(newdiv);}
else if(_el=="C"||_el=="D"||_el=="E"||_el=="F"||_el=="G"||_el=="H"||_el=="I"||_el=="J"||_el=="K"||_el=="L"){$('drag2').appendChild(newdiv);}
else{$('drag3').appendChild(newdiv);}
var dragable1 = DragHandler.attach($(_el));
}

//a helper function for several other routines.
function screensize(){
var x,y;
  if (parseInt(navigator.appVersion)>3||navigator.userAgent.indexOf('Opera') != -1) {
   if (navigator.appName=="Netscape"||navigator.userAgent.indexOf('Opera') != -1) {
    x = window.innerWidth;
    y = window.innerHeight;
   }
   if (navigator.appName.indexOf("Microsoft")!=-1) {
    x = document.body.offsetWidth;
    y = document.body.offsetHeight;
   }
  }
  return {x : x, y : y};
}

//reset checkmarks in layers dialog on page.load
function uncheckmof()
{
var t=document.getElementsByName('checkbox');
for(i=0;i<=t.length-1;i++)
  {
  document.getElementsByName('checkbox')[i].checked=false;
  }
}
//big function responsible for coordinate transformation and marker additions
var vx,vy,rad;

function bounder(icon,ex,ey){
if((ex>-40&&ex<180)&&(ey>-10&&ey<380)){return true;}
//get min max screen coords
//check the global screen flags;

var a = screensize();
var browser=sniff();
/*

vy=parseInt($('_vy').value);
vx=parseInt($('_vx').value);
rad = parseInt($('_rad').value);
*/
vy=120;
vx=55;
rad=10;
//make rad 15 for smaller icons




if (glob_height){var by=a.y;}else{

//need to sniff out Opera here
by=639;vx=34;vy=70;} //changed from 25, 80 bs 11/29

if (glob_width){var bx=a.x;}else{

//need to sniff out Opera here
bx=901;vy=76;}



var bounds = map.getBounds();
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
var x = screen2coords((ex+vx),0,bx,sw.x, ne.x); //was 27 before started messing with it
var y = screen2coords((ey+vy),0,by-137,ne.y, sw.y); //was by-137 before 55 before
var point = new GLatLng(y,x);
var _iconimg = new GIcon(G_DEFAULT_ICON);
var iconname="http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+icon+icon+".png";
_iconimg.image = iconname;
_iconimg.iconSize = new GSize(20, 36);
_iconimg.iconAnchor = new GPoint(rad, 36); //10 works for larger icons
var inc=parseInt(document.getElementById('_'+icon+'_').innerHTML);
document.getElementById('_'+icon+'_').innerHTML=inc+1;
document.getElementById('_'+icon+'_').style.visibility='visible';
var marker=new GMarker(point,{icon:_iconimg, draggable: true});
marker.id = icon+"-"+(inc+1)+"";
map.addOverlay(marker);
x=(Math.round(x*100000)/100000);
y=(Math.round(y*100000)/100000);
ptdrop(x,y,icon,inc+1);
	var popUp = document.createElement("DIV");
	popUp.style.fontFamily = "Verdana";
	popUp.style.fontSize = "11px";
	//popUp.style.height = "100px";
	popUp.setAttribute('id','ib'+marker.id);
	popUp.innerHTML='<textarea style="resize:none;margin:5px 0px 13px 5px;height:45px;width:195px;border:solid 1px #CCC;font-family:Verdana;font-size:11px;" id="txt'+marker.id+'"></textarea><br><a href="#" id="e" onclick="submitdesc(\''+marker.id+'\',\'txt'+marker.id+'\')");"><img src="./images/45.png" border="0" > Save</a>&nbsp;&nbsp;<img src=\'./images/splitter.png\'>&nbsp;&nbsp;<a href="#"  onclick="ptremove(\''+marker.id+'\');" id="e"><img src="./images/d.gif" border="0"> Delete</a>';

//  Uncomment if want a particular marker to automatically pop up annotation box
//if(icon=="B"){
//marker.openInfoWindowHtml(popUp);
//}
GEvent.addListener(marker, "click", function() {

        marker.openInfoWindowHtml(popUp);
        
      });

GEvent.addListener(marker, "dragend", function() {
var gll = new GLatLng;
gll = marker.getLatLng();
x=(Math.round(gll.lng()*100000)/100000);
y=(Math.round(gll.lat()*100000)/100000);
          ptmove(x,y, marker.id);
        });
}

//add points from the db on page load or marker deletion
function ptAddfromDb(icon,num,x,y,desc)
{
var point = new GLatLng(y,x);
var _iconimg = new GIcon(G_DEFAULT_ICON);
var iconname="http://www.landscapemap2.org/ecoservices/Icons/Alt_icons/"+icon+icon+".png";
_iconimg.image = iconname;
_iconimg.iconSize = new GSize(20, 36);
_iconimg.iconAnchor = new GPoint(10, 39);

var inc=parseInt(document.getElementById('_'+icon+'_').innerHTML);
document.getElementById('_'+icon+'_').innerHTML=inc+1;
document.getElementById('_'+icon+'_').style.visibility='visible';
//no!! must add them
var marker=new GMarker(point,{icon:_iconimg, draggable: true});
marker.id = icon+"-"+(num)+"";
map.addOverlay(marker);
	var popUp = document.createElement("DIV");
	popUp.setAttribute('id','ib'+marker.id);
	popUp.style.fontFamily = "Verdana";
	popUp.style.fontSize = "11px";
	popUp.style.height = "90px";
	//test for desc.
	popUp.innerHTML="";
	if(desc==""){popUp.innerHTML="<i>No description submitted.</i>";}
	else
	{
	popUp.innerHTML='"'+desc+'"';}
	popUp.innerHTML='<textarea style="resize:none;margin:5px 0px 13px 5px;height:45px;width:195px;border:solid 1px #CCC;font-family:Verdana;font-size:11px;" id="txt'+marker.id+'">'+desc+'</textarea><br><a href="#" id="e" onclick="submitdesc(\''+marker.id+'\',\'txt'+marker.id+'\')");"><img src="./images/45.png" border="0" > Save</a>&nbsp;&nbsp;<img src=\'./images/splitter.png\'>&nbsp;&nbsp;<a href="#"  onclick="ptremove(\''+marker.id+'\');" id="e"><img src="./images/d.gif" border="0"> Delete</a>';

GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(popUp);
      });

GEvent.addListener(marker, "dragend", function() {
var gll = new GLatLng;
gll = marker.getLatLng();
x=(Math.round(gll.lng()*100000)/100000);
y=(Math.round(gll.lat()*100000)/100000);
          ptmove(x,y, marker.id);
        });

}
//marker deletion routine
function ptremove(ptid)
{
//get a handle on the icon type
/*
var cat=ptid.split("-");
var ctr=parseInt($("_"+cat[0]+"_").innerHTML);
$("_"+cat[0]+"_").innerHTML = ctr-1;
if (ctr-1==0) { $("_"+cat[0]+"_").style.visibility="hidden";}
*/

//clear out all the tallies on the icons? there must be a better way...
//alert('You have entered ptremove function!');
for(i=65;i<81;i++)
{
var z=String.fromCharCode(i);
$('_'+z+'_').innerHTML="0";
$('_'+z+'_').style.visibility="hidden";
}
for(i=0;i<10;i++){
$('_'+i+'_').innerHTML="0";
$('_'+i+'_').style.visibility='hidden';
}

var url='http://www.landscapemap2.org/ecoservices/deletept.php?ptid='+ptid;
ajax(url);

}
///three functions used for coord transformation
function normalize(value, minimum,maximum){return (value - minimum) / (maximum - minimum);}
function interpolate(normValue,minimum,maximum){return minimum + (maximum - minimum) * normValue;}
function screen2coords(value, min1,max1, min2, max2) {return interpolate( normalize(value, min1, max1), min2,max2);}

  //validate form
  function validate()
  {
  var c=0;
  var a = document.getElementById('pass1').value;
  var b = document.getElementById('pass2').value;
  //test for blanks
  if (a==""||b=="")
  {opacity('float1',100,0,0);$('msg').innerHTML='&nbsp;&nbsp;Please Enter both parts of the Access Code.';c=1;}
  //Test for any letters
   var re = /^[0-9]*$/;
        if (!re.test(a)||!re.test(b)) {opacity('float1',100,0,0); 
  $('msg').innerHTML='&nbsp;&nbsp;Access code is all numbers';c=1;}
  //reset form fields to blank
  if(c==1){
  document.getElementById('pass1').value="";
  document.getElementById('pass2').value="";
  return
  }
  var url='http://www.landscapemap2.org/ecoservices/checklogin.php?groupID='+a+'&randomID='+b;
  //run to the db and check to make sure these values work
  ajax(url);
  }
  //the ajax routine - functions send urls to this routine and this does the AJAx
  function ajax(url) {
    try {
        var xmlhttp = GetXmlHttp();
        if (xmlhttp) {
            xmlhttp.open("GET", url, true);
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4) {
                    var result= xmlhttp.responseText;
                    eval(result);
                }
            };
            xmlhttp.send(null);
        }
    } catch(ex) {
        alert(ex.message);
    }
    }
    
  function GetXmlHttp() {
    var x = null;
    try {
        x = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            x = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            x = null;
        }
    }
    if (!x && typeof XMLHttpRequest != "undefined") {
        x = new XMLHttpRequest();
    }
    return x;
}
//used for the login screen to enable tabbing between the textboxes
function Tab(currentField, nextField,length)
{
length+=1;
var selectedText = document.selection;
if (document.selection)
{
if (selectedText.type == 'Text'&&currentField.focus())
{return}
}
//might need to set this up to browser detect

if (parseInt(currentField.value.length) == parseInt(length))
    {$(nextField).focus();}
}
//simplistic browser sniffer
function sniff(){
var b=0;
  if (parseInt(navigator.appVersion)>3) {
   b=1;//this gets FF
   }
  if (navigator.appName.indexOf("Microsoft")!==-1) {
  b=2;} //this gets IE
  if(navigator.userAgent.indexOf('Opera') !==-1){
  b=3;}  //This Gets Opera
  return b;
}
//Used for the value description dialog
function testfirst()
{
if($('float1').style.opacity !=="1"||$('float1').style.filter=="alpha(opacity=100)"||$('pass1').value==""||$('pass2').value=="")
{
$('msg').innerHTML="";
ajax('http://www.landscapemap2.org/ecoservices/getnew2.php')
$('submit').focus();
}
else
{
$('float1').style.border="1px #FF0000 solid";
var t=setTimeout("$('float1').style.border='1px rgb(150, 150, 150) solid'",500);
}
}
//submit description function
function submitdesc(ptid,desc)
{

var desc1 = document.getElementById(desc).value;
if(desc1==""){alert('You haven\'t entered any text!');return;}
var url='http://www.landscapemap2.org/ecoservices/insertdesc.php?ptid='+ptid+'&desc='+desc1;
ajax(url);
map.closeInfoWindow();
}
//when a point is added to the map it is also added to the db
function ptdrop(x,y,cat,num)
{
//get the map zoom level
var z=map.getZoom();
var t=map.getCurrentMapType().getName();
//commented out by BS 11/29/09
//var url="http://www.landscapemap2.org/ecoservices/testpopup.php";
//ajax(url);
var url="http://www.landscapemap2.org/ecoservices/addpt.php?x="+x+"&y="+y+"&cat="+cat+"&num="+num+"&z="+z+"&t="+t;
ajax(url);
}
//when a marker is dragged to a new location
function ptmove(x,y,catnum){
var url="http://www.landscapemap2.org/ecoservices/changept.php?x="+x+"&y="+y+"&catnum="+catnum;
ajax(url);
}


//Show or hide the info panel
function ShowHide(item) {
    if (item.style.visibility !== 'hidden') {
    opacity(item.id,90,0,100);
    } else {
     opacity(item.id,0,90,100);
    }
}
//opsacit
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
            
        }
        setTimeout("$('"+id+"').style.visibility='hidden'",100);
    } else if(opacStart < opacEnd) {
     $(id).style.visibility='visible';
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
		 }
    }
//change the opacity for different browsers
function changeOpac(opacity, id) {

    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
	if (id!="dBox"){
    object.filter = "alpha(opacity=" + opacity + ")";}
	//if(opacity==100 && id=="dBox")
	//{object.filter="none";}
}

function showDBox()
{
if ($('dBox').style.visibility=="hidden")
{
opacity("dBox_bg",0,90,100);
opacity("dBox",0,100,100);
}
else
{
opacity("dBox_bg",90,0,100);
opacity("dBox",100,0,100);
}
}


//check to make sure the user has added points to the map before continuing on to the survey.
function checkpts()
{
var url='http://www.landscapemap2.org/ecoservices/checkpts.php';
ajax(url);
}
//when a point is deleted all overlays are cleared and re-added - this checks checkboxes and adds appropriate layers
function checkchecks()
{
var t=document.getElementsByName('checkbox');
for(i=0;i<t.length;i++)
{
_KML(t[i]);
}
}
function dsc(a)
{
var x=a.replace("anno_","");

var descriptions={"0": "I value these places because they provide fresh water for households, for irrigating farmland, or for business/industry.", "1": "I value these places because they provide plants or animals to eat, including game meat, fish, fruits, vegetables, or mushrooms.", "2": "I value these places because they provide wood products, animal feed (e.g., grass, leaves), firewood, or other useful natural materials.", "3": "I value these places because they provide wild seeds for growing plants and crops.", "4": "I value these places because they provide plants that can be used for medicines, drugs, or natural remedies.", "5": "I value these places because they provide plants, animals, rocks, minerals, or other materials for fashion, clothing, crafts, or decoration.", "6": "I value these places because they have attractive or pleasing landscapes.", "7": "I value these places because they provide recreational opportunities.", "8": "I value these places because they provide opportunities to express and appreciate art, music, history, and other pieces of human culture.", "9": "I value these places because they provide opportunities for spiritual or religious activities.", "A": "I value these places because they provide opportunities to understand and learn about the natural world.", "B": "I value these places because they provide opportunities to interact with family, neighbors, friends, and other people.", "C": "I value these places because they help clean the air and regulate climate by influencing the temperature, precipitation, and the absorption and reflection of energy from the sun.", "D": "I value these places because they help filter and purify water, maintain natural irrigation or drainage of water (e.g., rivers, wetlands), reduce flooding, or provide channels for the flow of water.", "E": "I value these places because they prevent soil loss caused by wind, water, fire, and other erosion processes.", "F": "I value these places because they provide pollination sources for wild plants or agricultural crops, or provide habitat for pollinating species such as bees and insects.", "G": "I value these places because they help clean the air and regulate climate by influencing the temperature, precipitation, and the absorption and reflection of energy from the sun.", "H": "I value these places because they provide organisms (insects, predators) that keep plant and animal populations in check to reduce agricultural pests and carriers of human disease.", "I": "I value these places because they buffer or reduce the impacts of hazards such as earthquakes, landslides, and natural events such as storms, floods, drought, and wildfires.", "J": "I value these places because they provide habitat for wild plants and animals as well as places for new generations to grow.", "K": "I value these places because they provide for the formation of new soil through the weathering of rock and accumulation of organic matter.", "L": "I value these places because they provide for the collection, storage, processing and reuse of essential nutrients for plants such as nitrogen and phosphorous.", "M": "These places are at risk to future wildfire.", "N": "These places are at risk to future development--residential, commercial, or industrial.", "O": "These places are at risk to future extraction of natural resources: timber, grazing, mining, or energy development.", "P": "These places are at risk to other potential threats--click on icon to write the specific type of threat.", "X": "Move your mouse over a value category to see its description"};

var response="";
if(a!="X") {response += "<img src=./icn/"+a+".png style='padding:0px 7px 0px 0px;'>"}
response +=descriptions[a];
return response;
}


