//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  Javascript code for Version 3 of Landscape Values Map
//  Copyright Landscape Values Institute 2010
//  http://www.landscapevalues.org/
//
//  Coding by Ben Sainsbury and Dr. Greg Brown
//  
// Last edited 6/1/2009 : BS
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Configurables

	  /* Server Name */
	  /* Production */
	var server="http://www.landscapemap2.org/swparks3/";
	/* Development */
	//var server="http://localhost:64739/swParks3/";
	
	/* MapCenter */
	//var mapCenter={"x":142.0318,"y":-37.9324,"zoom":9};
    var mapCenter={"x":141.7,"y":-37.8324,"zoom":9};
	var mapBounds={"xmin":140.960, "ymin":-38.485, "xmax":142.465, "ymax":-37.111};
	/* Number of Markers */
	var numMarkers=47;
	var ptOrig={"x":null, "y":null};
var map;
var ge;
var X_coord,Y_coord;
var getab=1;
var gtab=1;
var curMode="GMaps";
var curType="Roads";
var Tab1=null;
var Tab2=null;
var Tab3=null;
var bIsLoad =true;
var mapping=false;
var myMarker=null;
var placemark;
var curMarker="";
var _name="";
var dragInfo = null;
var dragging=false;
var buttonDown = false;
var markerHash = [];
var markerArray = [];

for (i=0;i<numMarkers;i++){markerHash.push(0);}
	 
function $(el) {
    return document.getElementById(el);
}

function debug(str) {
    $('debug').innerHTML += str + "<br>";
}

// Screensize method - needed for resize method below

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
    };
}

// Resize method - runs on page load and on window resize

  //used for the consent page
  
function valcheck()
{

{var url='include/consent2.php';
AJAX(url);
}
}
  
//Used for the value description dialog and index.php
function testfirst()
{
if($('float1').style.opacity !=="1"||$('float1').style.filter=="alpha(opacity=100)"||$('pass1').value==""||$('pass2').value=="")
{
$('msg').innerHTML="";
AJAX('include/getnew2.php')
$('submit').focus();
}
else
{
$('float1').style.border="1px #FF0000 solid";
var t=setTimeout("$('float1').style.border='1px rgb(150, 150, 150) solid'",500);
}
}


// Global width and height vars

var glob_height=true;
var glob_width=true;

function resize() {
    var browser = sniff();
    var a = screensize();
    var g = 0;
    //test if we're losing the left panel...
    if ($('body')) {
        if (a.y < 740) //the screen height is less than 720px
        {
            glob_height = false;
            //$('_h').innerHTML='h';
            if ($('content')) {
                $('content').style.height = "700px";
            } //works
            if ($('map3d')) {
                $('map3d').style.height = "615px";
            } //works
            if ($('survey')) {
                $('survey').style.height = "620px";
            } //works
            if ($('content2')) {
                $('content2').style.height = "620px";
            } //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;
                // $('_w').innerHTML='w';
                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; //$('_h').innerHTML='';
            }
            //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 +12+ "px";
            }
            if ($('map3d')) {
                $('map3d').style.height = a.y - g +23+ "px";
            }
            if ($('survey')) {
                $('survey').style.height = a.y - g - 10+ "px";
            }
            if ($('content2')) {
                $('content2').style.height = a.y - g -37 + "px";
            }

        }
        if (a.x < 900) {
            glob_width = false;
            //$('_w').innerHTML='w';
            var f = 900;
            //$('toptable').style.width=f+"px";
    $('topnavbar').style.width=f+"px";
    $('bottomnavbar').style.width=f+"px";
    if($('map3d')){$('map3d').style.width=f+"px";}

	  
        }
        else {
            glob_width = true;
            // $('_w').innerHTML='';
            //$('toptable').style.width = "100%";
            $('topnavbar').style.width = "100%";
            $('bottomnavbar').style.width = "100%";
            if ($('content')) {
                $('content').style.width = "100%";
            }
            if ($('map3d')) {
                $('map3d').style.width = "100%";
            }
            //works
        }
    }
}

// Browser sniffer - nothing too exciting here...

function sniff() {
    var b = 0;
    if (navigator.userAgent.indexOf('Firefox') !== -1) {
        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
    if (navigator.userAgent.indexOf('Chrome') !== -1) {
        b = 4; //this gets FF
    }
    return b;
}

// Returns the number of markers placed on the map.

function markerCount(mrkr) {

    //takes a marker type value and returns the cumulative number
    markerHash[mrkr]++;
    return markerHash[mrkr];
}

// pads a number for use in getting the right marker icon.

function pad(num){
   var str = '' + num;
   while(str.length<2){
      str = '0'+str;
   }
   return str;
}

// Used to embed controls in the GMaps map frame

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);
}

// Initializes *The Map* - starts in GMaps mode.

var marker_mouseup_event, marker_mousemove_event, geoBound, geoParks, geoPhotos;
var myIcon;
//if(catx){google.load("maps", "2.x");}
function init() {

map = new GMap2(document.getElementById('map3d'));
map.setCenter(new GLatLng(mapCenter.y,mapCenter.x), mapCenter.zoom);
map.enableScrollWheelZoom();
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_HYBRID_MAP);
myIcon = new GIcon();
myIcon.iconSize= new GSize(28,28);
myIcon.iconAnchor = new GPoint(14,14);
myIcon.infoWindowAnchor = new GPoint(16,8);
markerOptions = { icon:myIcon,draggable:true};
myMarker = new GMarker(new GLatLng(37, -122),markerOptions);
map.addOverlay(myMarker);
myMarker.hide();
var scale = new GScaleControl();
map.addControl(scale);
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);

geoBound = new GGeoXml("http://www.landscapemap2.org/swparks3/kml/studyboundary.kmz");
map.addOverlay(geoBound);
geoParks = new GGeoXml("http://www.landscapemap2.org/swparks3/kml/parkres6.kmz");
map.addOverlay(geoParks);
geoPhotos = new GLayer("com.panoramio.all");

geoPhotos.hide();
map.addOverlay(geoPhotos);

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

var tabBox = new makeHtmlControl($('tabBox'));
map.addControl(tabBox, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(11, 10)));

var btnCenter=new makeHtmlControl($('btnCenter'));
map.addControl(btnCenter, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(67, 495)));

var btnSurvey=new makeHtmlControl($('btnSurvey'));
map.addControl(btnSurvey, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(24, 530)));

var btnMappingMode=new makeHtmlControl($('pnlMappingMode'));
map.addControl(btnMappingMode, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(400, 8)));

// add 'Earth' as one of the map types
map.addMapType(G_SATELLITE_3D_MAP);

$('debug').innerHTML = " v1.3.4";
addGMapsMouseListeners(); 

 GEvent.addListener(map, "tilesloaded", function() {
   map.removeOverlay(geoParks);
   map.addOverlay(geoParks);
    });

//Add the event listener for appropriate mapping scale
GEvent.addListener(map, "zoomend", function(oldZoom,newZoom) {
  if((newZoom==14 && oldZoom==13) | newZoom > 13 ){
  $('modeImage').src="icons/okToMap.png";
  mapping = true;
  }
  else if((newZoom==13 && oldZoom==14) | newZoom < 14){
  $('modeImage').src="icons/browsingOnly.png";
  mapping = false;
  }
  for (i in markerArray)
{
if(mapping){markerArray[i].enableDragging();}else{markerArray[i].disableDragging();}
}


});
// do stuff with Earth when the user switches to it
GEvent.addListener(map, 'maptypechanged', function() {

	if(map.getCurrentMapType().getName() !="Earth"){
	switchTab(getab);$('tab'+getab+'_markers').style.visibility="visible";
	curType = map.getCurrentMapType().getName();
	if (curMode=="GEarth"){
	db_reloadPts("GMaps");
	// Check to make sure a dialog box isn't open at this point.
	if($('instbox').style.visibility!=='hidden'||$('mrkrDescBox').style.visibility!=='hidden'){destroyNativeHTMLButton();}
	curMode="GMaps";
	myMarker = new GMarker(new GLatLng(37, -122),markerOptions);
	map.addOverlay(myMarker);
	myMarker.hide();
	addGMapsMouseListeners();
	}
	}
	else
	{
	if($('instbox').style.visibility!=='hidden'||$('mrkrDescBox').style.visibility!=='hidden'){createNativeHTMLButton(379, 16, 701, 477);}
	
	curMode="GEarth";
	curType="GEarth";
    if (ge) 
	{db_reloadPts("GEarth");return;}
	
	$('tab1_markers').style.visibility="hidden";
	$('tab2_markers').style.visibility="hidden";
	$('tab3_markers').style.visibility="hidden";
	 
    map.getEarthInstance(function(instance) {
	ge=instance;
    ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS);
    ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_INSET_PIXELS);
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
    ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
	GEvent.removeListener(marker_mousemove_event);
	GEvent.removeListener(marker_mouseup_event);
	
	db_reloadPts("GEarth");
    doStuffWithEarth();
	_KML($('boundary'));
    });
	}
	
  });
  // Add a move listener to restrict the bounds range
      // GEvent.addListener(map, "move", function() {
        // checkBounds();
		// //alert('test');
      // });
	// //var mapCenter={"x":142.0318,"y":-37.9324,"zoom":9};
      // // The allowed region which the whole map must be within
      // var allowedBounds = new GLatLngBounds(new GLatLng(-36,143), new GLatLng(-38,141));
      
      // // If the map position is out of range, move it back
      // function checkBounds() {
	  // alert('tes');
        // // Perform the check and return if OK
        // if (allowedBounds.contains(map.getCenter())) {
          // return;
        // }
        // // It`s not OK, so find the nearest allowed point and move there
        // var C = map.getCenter();
        // var X = C.lng();
        // var Y = C.lat();

        // var AmaxX = allowedBounds.getNorthEast().lng();
        // var AmaxY = allowedBounds.getNorthEast().lat();
        // var AminX = allowedBounds.getSouthWest().lng();
        // var AminY = allowedBounds.getSouthWest().lat();

        // if (X < AminX) {X = AminX;}
        // if (X > AmaxX) {X = AmaxX;}
        // if (Y < AminY) {Y = AminY;}
        // if (Y > AmaxY) {Y = AmaxY;}
        // //alert ("Restricting "+Y+" "+X);
        // map.setCenter(new GLatLng(Y,X));
      // }
}




// Function to recenter the map on button click
function recenter()
{
map.setCenter(new GLatLng(mapCenter.y,mapCenter.x), mapCenter.zoom);
// Added by Greg 11/03/10 to disable mapping after centering at zoom level 9
$('modeImage').src="icons/browsingOnly.png";
mapping = false;
for (i in markerArray)
{
markerArray[i].disableDragging();
}
  // db_reloadPts("GMaps");
    // _KML($('boundary'));
    // _KML($('parks'));
	// _KML($('photos'));
  // myMarker = new GMarker(new GLatLng(37, -122),markerOptions);
	// map.addOverlay(myMarker);
	// myMarker.hide();
}

// Add listeners to GMaps tabbox and markers

function addGMapsMouseListeners(){
	marker_mouseup_event = GEvent.addDomListener(map.getContainer(), "mouseup", function(evt)
{ if(dragging){dragging=false;
myMarker.hide();
if(Y_coord<mapBounds.ymax && Y_coord>mapBounds.ymin && X_coord<mapBounds.xmax && X_coord>mapBounds.xmin){
markerOptions = { icon:myIcon,draggable:true};
var marker = new GMarker(new GLatLng(Y_coord,X_coord), markerOptions);
var mrkrNum = markerCount(curMarker);
marker.id=curMarker + ":" + mrkrNum;

var popUp = document.createElement("DIV");
	popUp.style.fontFamily = "Verdana";
	popUp.style.fontSize = "11px";
	popUp.setAttribute('id','ib'+marker.id);
	popUp.innerHTML="<b>"+catx[curMarker]+'</b><br><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><img src="http://www.landscapemap2.org/swparks3/images/45.png" border="0" > <a href="#" class="e1" onclick="db_addDesc(\''+marker.id+'\',$(\'txt'+marker.id+'\').value);map.closeInfoWindow();">Save</a>&nbsp;&nbsp;<img src=\'http://www.landscapemap2.org/ben/images/splitter.png\'>&nbsp;&nbsp;<img src="icons/delete-icon.png" border="0"> <a href="#"  onclick="db_deleteMarker(\''+marker.id+'\');" class="e1">Delete</a>';
	
GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(popUp);
      });
 
GEvent.addListener(marker, "dragstart", function(gll) {
ptOrig.x=gll.lng().toFixed(6);
ptOrig.y=gll.lat().toFixed(6);
});
 
GEvent.addListener(marker, "dragend", function(gll) {
if(gll.lng()>mapBounds.xmin && gll.lng()<mapBounds.xmax && gll.lat()<mapBounds.ymax && gll.lat()>mapBounds.ymin){
db_moveMarker(marker.id,gll.lng().toFixed(6),gll.lat().toFixed(6));
}
else
{
alert('You\'ve moved the marker outside of the study area bounds.');
marker.setLatLng(new GLatLng(ptOrig.y,ptOrig.x));}

        });
markerArray.push(marker);
map.addOverlay(marker);
db_addMarker(marker.id,X_coord,Y_coord);
}
else{
alert('Marker is outside the bounds of the study area.');}
}
 });
 
 marker_mousemove_event = GEvent.addListener(map, "mousemove", function(point){
 if(myMarker.isHidden && dragging){
 myMarker.show();
 myMarker.setLatLng(new GLatLng(point.lat().toFixed(6),point.lng().toFixed(6)));}
 X_coord=point.lng().toFixed(6);
Y_coord=point.lat().toFixed(6);
});
}

// callBack function when map is switched to GE Mode

function doStuffWithEarth() {
	
	 createScreenOverlayButton(10, 10, 317, 474, 'Tab4', 20, 'Tab4', true);
	 createScreenOverlayButton(10, 10, 317, 474, 'Tab3', 20, 'Tab3', true);
	createScreenOverlayButton(10, 10, 317, 474, 'Tab2', 20, 'Tab2', true);
    createScreenOverlayButton(10, 10, 317, 474, 'Tab1', 20, 'Tab1', true);
	createScreenOverlayButton(67, 495, 133, 28, 'btnCenter', 22, 'btnCenter', true);
	createScreenOverlayButton(24, 530, 219, 30, 'btnSurvey', 22, 'btnSurvey', true);
    //create the buttons
    createScreenOverlayButton(275, 60, 28, 28, '00', 21, 'Tab1_00', true, 1);
    createScreenOverlayButton(275, 91, 28, 28, '01', 21, 'Tab1_01', true, 1);
    createScreenOverlayButton(275, 122, 28, 28, '02', 21, 'Tab1_02', true, 1); 
    createScreenOverlayButton(275, 153, 28, 28, '03', 21, 'Tab1_03', true, 1); 
    createScreenOverlayButton(275, 184, 28, 28, '04', 21, 'Tab1_04', true, 1); 
    createScreenOverlayButton(275, 215, 28, 28, '05', 21, 'Tab1_05', true, 1); 
    createScreenOverlayButton(275, 246, 28, 28, '06', 21, 'Tab1_06', true, 1); 
    createScreenOverlayButton(275, 277, 28, 28, '07', 21, 'Tab1_07', true, 1); 
    createScreenOverlayButton(275, 308, 28, 28, '08', 21, 'Tab1_08', true, 1); 
    createScreenOverlayButton(275, 339, 28, 28, '09', 21, 'Tab1_09', true, 1);
    createScreenOverlayButton(275, 60, 28, 28, '10', 21, 'Tab2_10', false, 2);
    createScreenOverlayButton(275, 91, 28, 28, '11', 21, 'Tab2_11', false, 2);
    createScreenOverlayButton(275, 122, 28, 28, '12', 21, 'Tab2_12', false, 2);
    createScreenOverlayButton(275, 153, 28, 28, '13', 21, 'Tab2_13', false, 2);
    createScreenOverlayButton(275, 184, 28, 28, '14', 21, 'Tab2_14', false, 2);
    createScreenOverlayButton(275, 215, 28, 28, '15', 21, 'Tab2_15', false, 2);
    createScreenOverlayButton(275, 246, 28, 28, '16', 21, 'Tab2_16', false, 2);
    createScreenOverlayButton(275, 277, 28, 28, '17', 21, 'Tab2_17', false, 2);
    createScreenOverlayButton(275, 308, 28, 28, '18', 21, 'Tab2_18', false, 2); 
    createScreenOverlayButton(275, 339, 28, 28, '19', 21, 'Tab2_19', false, 2); 
    createScreenOverlayButton(275, 370, 28, 28, '20', 21, 'Tab2_20', false, 2);
    createScreenOverlayButton(275, 60, 28, 28, '21', 21, 'Tab3_21', false, 3);
    createScreenOverlayButton(275, 91, 28, 28, '22', 21, 'Tab3_22', false, 3);
    createScreenOverlayButton(275, 122, 28, 28, '23', 21, 'Tab3_23', false, 3);
    createScreenOverlayButton(275, 153, 28, 28, '24', 21, 'Tab3_24', false, 3);
    createScreenOverlayButton(275, 184, 28, 28, '25', 21, 'Tab3_25', false, 3);
    createScreenOverlayButton(275, 215, 28, 28, '26', 21, 'Tab3_26', false, 3);
    createScreenOverlayButton(275, 246, 28, 28, '27', 21, 'Tab3_27', false, 3);
    createScreenOverlayButton(275, 277, 28, 28, '28', 21, 'Tab3_28', false, 3);
    createScreenOverlayButton(275, 308, 28, 28, '29', 21, 'Tab3_29', false, 3);
    createScreenOverlayButton(275, 339, 28, 28, '30', 21, 'Tab3_30', false, 3);
    createScreenOverlayButton(275, 370, 28, 28, '31', 21, 'Tab3_31', false, 3);
    createScreenOverlayButton(275, 401, 28, 28, '32', 21, 'Tab3_32', false, 3);
    createScreenOverlayButton(275, 432, 28, 28, '33', 21, 'Tab3_33', false, 3);
    createScreenOverlayButton(275, 60, 28, 28, '34', 21, 'Tab4_34', false, 4);
    createScreenOverlayButton(275, 91, 28, 28, '35', 21, 'Tab4_35', false, 4);
    createScreenOverlayButton(275, 122, 28, 28, '36', 21, 'Tab4_36', false, 4);
    createScreenOverlayButton(275, 153, 28, 28, '37', 21, 'Tab4_37', false, 4);
    createScreenOverlayButton(275, 184, 28, 28, '38', 21, 'Tab4_38', false, 4);
    createScreenOverlayButton(275, 215, 28, 28, '39', 21, 'Tab4_39', false, 4);
    createScreenOverlayButton(275, 246, 28, 28, '40', 21, 'Tab4_40', false, 4);
    createScreenOverlayButton(275, 277, 28, 28, '41', 21, 'Tab4_41', false, 4);
    createScreenOverlayButton(275, 308, 28, 28, '42', 21, 'Tab4_42', false, 4);
    createScreenOverlayButton(275, 339, 28, 28, '43', 21, 'Tab4_43', false, 4);
    createScreenOverlayButton(275, 370, 28, 28, '44', 21, 'Tab4_44', false, 4);
    createScreenOverlayButton(275, 401, 28, 28, '45', 21, 'Tab4_45', false, 4);
    createScreenOverlayButton(275, 432, 28, 28, '46', 21, 'Tab4_46', false, 4);
	  addListeners();
	  swapTab(gtab);
}

// Create the screen overlays for GE mode

function createScreenOverlayButton(x, y, width, height, _icon, drawOrder, name, visible, tab) {
    var _addOverlayForState = function () {
        var icon = ge.createIcon('');
        icon.setHref(server + "icons/"+ _icon + '.png');
        var overlay = ge.createScreenOverlay('');
        overlay.setDrawOrder(drawOrder);
        overlay.setVisibility(visible);
        overlay.setIcon(icon);
        overlay.setName(name);
        overlay.getOverlayXY().set(x, ge.UNITS_PIXELS, y, ge.UNITS_INSET_PIXELS);
        overlay.getScreenXY().set(0, ge.UNITS_FRACTION, 1, ge.UNITS_FRACTION);
        overlay.getSize().set(width, ge.UNITS_PIXELS, height, ge.UNITS_PIXELS);
        ge.getFeatures().appendChild(overlay);
        return overlay;
    };

    //if its a button and not a tab box
    if (drawOrder != 20) {
        var overlayReg = _addOverlayForState();
        var overlayHover = _addOverlayForState();

		if(drawOrder==21){
        google.earth.addEventListener(ge.getWindow(), 'mousemove', function (evt) {
            if (_isMouseOnButton(evt.getClientX(), evt.getClientY())) {
                if (getab == tab && overlayHover.getVisibility() == false) {
                    overlayHover.setVisibility(true);
                }
            }
            else if (getab == tab && overlayHover.getVisibility() == true) {
                overlayHover.setVisibility(false);
            }
        });
}

else if(drawOrder==22) //for the buttons
	{ google.earth.addEventListener(ge.getWindow(), 'mousemove', function (evt) {
            if (_isMouseOnButton(evt.getClientX(), evt.getClientY())) {
                    overlayHover.setVisibility(true);
            }
            else {
                overlayHover.setVisibility(false);
            }
        });
		
		google.earth.addEventListener(ge.getWindow(),'click', function (evt) {
		 if (_isMouseOnButton(evt.getClientX(), evt.getClientY())) {
		 
		 if(name=='btnCenter')
		 {
		 //re-center the map
		  var la = ge.createLookAt('');
    la.set(mapCenter.y,mapCenter.x, 10000,ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 254000);
    ge.getView().setAbstractView(la);
		 }
		 else
		 {
		 // go to survey
		 // Note that we could check to make sure the user has placed markers.
		 //window.location="survey.php";
		 //Changed by Ben 10/4/10
		 checkPts();
		 }
		 }
		});
}
		
        var _isMouseOnButton = function (mx, my) {
            return x <= mx && mx <= x + width && y <= my && my <= y + height;
        };

    }

    else if (name == 'Tab1') {
        Tab1 = _addOverlayForState();
    }
    else if (name == 'Tab2') {
        Tab2 = _addOverlayForState();
        Tab2.setVisibility(false);
    }
    else if (name == 'Tab3') {
        Tab3 = _addOverlayForState();
        Tab3.setVisibility(false);
    }
	else if (name == 'Tab4') {
        Tab4 = _addOverlayForState();
        Tab4.setVisibility(false);
    }
    else {}

    var buttonDown = false;

}

 //Changed by Ben 10/4/10
// Check to make sure they've added at least 1 point.
function checkPts(){
AJAX('http://www.landscapemap2.org/swparks3/checkpts.php');
}


// Hide GE overlays

function hideOverlay(tab) {

    var c = ge.getFeatures().getFirstChild();
    while (c) {
        var s = c.getNextSibling();
        if (c.getName().indexOf(tab) != -1) {
            c.setVisibility(false);
        }
        c = s;
    }
}

// Show GE overlays

function showOverlay(tab) {
    var c = ge.getFeatures().getFirstChild();
    while (c) {
        var s = c.getNextSibling();
        if (c.getName().indexOf(tab) != -1) {
            c.setVisibility(true);
        }
        c = s;
    }
}

// Swap tab function for GE mode

function swapTab(tab) {
    if (getab == tab) {
        return false;
    }
    if (tab == 1) {
        Tab1.setVisibility(true);
        showOverlay('Tab1_');
    }
    else if (tab == 2) {
        Tab2.setVisibility(true);
        showOverlay('Tab2_');
    }
	 else if (tab == 3) {
        Tab3.setVisibility(true);
        showOverlay('Tab3_');
    }
    else if (tab==4) {
        Tab4.setVisibility(true);
        showOverlay('Tab4_');
    }

    if (getab == 1) {
        Tab1.setVisibility(false);
        hideOverlay('Tab1_');
    }
    else if (getab == 2) {
        Tab2.setVisibility(false);
        hideOverlay('Tab2_');
    }
	else if (getab == 3) {
        Tab3.setVisibility(false);
        hideOverlay('Tab3_');
    }
    else if(getab == 4){
        Tab4.setVisibility(false);
        hideOverlay('Tab4_');
    }
   getab = tab;
}

// GE event listeners

function addListeners() {
    google.earth.addEventListener(ge.getWindow(), 'mousedown', function (evt) {
        if (evt.getTarget().getType() == 'KmlPlacemark' && evt.getTarget().getSnippet().indexOf(":")!=-1) {

            if (evt.getButton() == 0) {
                //left click == move existing placemark
                var placemark = evt.getTarget();
                dragInfo = {
                    placemark: evt.getTarget(),
                    dragged: false,
                    preExist: true,
                    y: evt.getLatitude(),
                    x: evt.getLongitude()
                }
            };
        }
        else if (evt.getClientX() > 275 && evt.getClientX() < 305 && evt.getClientY() > 60 && evt.getClientY() < 463) {

            var icony = evt.getClientY();
	
            if (icony > 60 && icony < 91) {
                if (getab == 1) {
                    _name = catx[0];
                    curMarker = 0;
                }
                else if (getab == 2) {
                    _name = catx[10];
                    curMarker = 10;
                }
				else if (getab == 3) {
                    _name = catx[21];
                    curMarker = 21;
                }
                else {
                    _name = catx[34];
                    curMarker = 34;
                }
            }
            else if (icony > 91 && icony < 122) {
                if (getab == 1) {
                    _name = catx[1];
                    curMarker = 1;
                }
                else if (getab == 2) {
                    _name =catx[11];
                    curMarker = 11;
                }
				else if (getab == 3) {
                    _name = catx[22];
                    curMarker = 22;
                }
                else {
                    _name = catx[35];
                    curMarker = 35;
                }
            }
            else if (icony > 122 && icony < 153) {
                if (getab == 1) {
                    _name =catx[2];
                    curMarker = 2;
                }
                else if (getab == 2) {
                    _name = catx[12];
                    curMarker = 12;
                }
					else if (getab == 3) {
                    _name = catx[23];
                    curMarker = 23;
                }
                else {
                    _name = catx[36];
                    curMarker = 36;
                }
            }
            else if (icony > 153 && icony < 184) {
                if (getab == 1) {
                    _name = catx[3];
                    curMarker = 3;
                }
                else if (getab == 2) {
                    _name = catx[13];
                    curMarker = 13;
                }
					else if (getab == 3) {
                    _name = catx[24];
                    curMarker = 24;
                }
                else if(getab==4){
                    _name = catx[37] ;
                    curMarker = 37;
                }
            }
            else if (icony > 184 && icony < 215) {
                if (getab == 1) {
                    _name = catx[4];
                    curMarker = 4;
                }
                else if (getab == 2) {
                    _name = catx[14];
                    curMarker = 14;
                }
					else if (getab == 3) {
                    _name = catx[25];
                    curMarker = 25;
                }
                else if(getab==4){
                    _name = catx[38] ;
                    curMarker = 38;
                }
            }
           else if (icony > 215 && icony < 246) {
                if (getab == 1) {
                    _name = catx[5];
                    curMarker = 5;
                }
                else if (getab == 2) {
                    _name = catx[15];
                    curMarker = 15;
                }
					else if (getab == 3) {
                    _name = catx[26];
                    curMarker = 26;
                }
                else if(getab==4){
                    _name = catx[39] ;
                    curMarker = 39;
                }
            }
           else if (icony > 246 && icony < 277) {
                if (getab == 1) {
                    _name = catx[6];
                    curMarker = 6;
                }
                else if (getab == 2) {
                    _name = catx[16];
                    curMarker = 16;
                }
					else if (getab == 3) {
                    _name = catx[27];
                    curMarker = 27;
                }
                else if(getab==4){
                    _name = catx[40] ;
                    curMarker = 40;
                }
            }
           else if (icony > 277 && icony < 308) {
                if (getab == 1) {
                    _name = catx[7];
                    curMarker = 7;
                }
                else if (getab == 2) {
                    _name = catx[17];
                    curMarker = 17;
                }
					else if (getab == 3) {
                    _name = catx[28];
                    curMarker = 28;
                }
                else if(getab==4){
                    _name = catx[41] ;
                    curMarker = 41;
                }
            }
            else if (icony > 308 && icony < 339) {
                if (getab == 1) {
                    _name = catx[8];
                    curMarker = 8;
                }
                else if (getab == 2) {
                    _name = catx[18];
                    curMarker = 18;
                }
					else if (getab == 3) {
                    _name = catx[29];
                    curMarker = 29;
                }
                else if(getab==4){
                    _name = catx[42] ;
                    curMarker = 42;
                }
            }
			     else if (icony > 339 && icony < 370) {
                if (getab == 1) {
                    _name = catx[9];
                    curMarker = 9;
                }
                else if (getab == 2) {
                    _name = catx[19];
                    curMarker = 19;
                }
					else if (getab == 3) {
                    _name = catx[30];
                    curMarker = 30;
                }
                else if(getab==4){
                    _name = catx[43] ;
                    curMarker = 43;
                }
            }
			     else if (icony > 370 && icony < 401) {
               if (getab == 2) {
                    _name = catx[20];
                    curMarker = 20;
                }
					else if (getab == 3) {
                    _name = catx[31];
                    curMarker = 31;
                }
                else if(getab==4){
                    _name = catx[44] ;
                    curMarker = 44;
                }
            }     else if (icony > 401 && icony < 432) {
              if (getab == 3) {
                    _name = catx[32];
                    curMarker = 32;
                }
                else if(getab==4){
                    _name = catx[45] ;
                    curMarker = 45;
                }
            }
			else if (icony > 432 && icony < 463) {
              if (getab == 3) {
                    _name = catx[33];
                    curMarker = 33;
                }
                else if(getab==4){
                    _name = catx[46] ;
                    curMarker = 46;
                }
            }
			
            buttonDown = true;
            var mrkrNum = markerCount(curMarker);
			
            placemark = ge.createPlacemark('');
            //placemark.setName(_name);
			placemark.setSnippet(curMarker+":"+mrkrNum);
            var _icon_ = ge.createIcon('');
            _icon_.setHref(server +"icons/"+ pad(curMarker) + '.png');
            var style = ge.createStyle(''); //create a new style
            style.getIconStyle().setIcon(_icon_); //apply the icon to the style
            style.getIconStyle().setScale(0.8); //apply the icon to the style
			style.getIconStyle().getHotSpot().set(0.3, ge.UNITS_FRACTION, 0.3, ge.UNITS_FRACTION);
            placemark.setStyleSelector(style); //apply the style to the placemark
            var point = ge.createPoint('');
            point.setLatitude(evt.getLatitude());
            point.setLongitude(evt.getLongitude());
            placemark.setGeometry(point);

            ge.getFeatures().appendChild(placemark);

            evt.preventDefault(); //this prevents the map pan on the button click - !!KEEP!!
            dragInfo = {
                placemark: placemark,
                dragged: true
            };

        }

    });

    google.earth.addEventListener(ge.getWindow(), 'mousemove', function (evt) {

        var x = evt.getClientX();
        var y = evt.getClientY();

        if (y > 11 && y < 41) {
            if (x > 14 && x < 85) {
                swapTab(1);
            } else if (x > 84 && x < 158) {
                swapTab(2);
            } else if (x > 158 && x < 235) {
                swapTab(3);
            } else if (x > 235 && x < 306) {
                swapTab(4);
            }
        }

        if (dragInfo) {
            evt.preventDefault();
            var point = dragInfo.placemark.getGeometry();
            point.setLatitude(evt.getLatitude());
            point.setLongitude(evt.getLongitude());
            dragInfo.dragged = true;
        }

        if (buttonDown) {
            event.preventDefault();
            return false;
        }

    });
	
    google.earth.addEventListener(ge.getWindow(), 'mouseup', function (evt) {

        if (!dragInfo.preExist) {
		if(evt.getLongitude() > mapBounds.xmin && evt.getLongitude() < mapBounds.xmax && evt.getLatitude() > mapBounds.ymin && evt.getLatitude() < mapBounds.ymax){

		//new marker dropped
            buttonDown = false;
            evt.preventDefault();
			
			//this is/was for GMaps markers...
			//var marker = new GMarker(new GLatLng(evt.getLatitude(),evt.getLongitude()));
			//map.addOverlay(marker);
			//debug(evt.getTarget().getSnippet()+" "+ evt.getLongitude().toFixed(6)+" "+ evt.getLatitude().toFixed(6));
            db_addMarker(evt.getTarget().getSnippet(), evt.getLongitude().toFixed(6), evt.getLatitude().toFixed(6));
            dragInfo = null;
        }
		else{

		alert('Marker is outside the study area bounds.');
		var c = ge.getFeatures().getFirstChild();
        while (c) {
            var s = c.getNextSibling();
            if (c.getSnippet() == dragInfo.placemark.getSnippet()) {
                ge.getFeatures().removeChild(c);
            }
            c = s;
        }
		dragInfo = null;
		}
		}
        else //preExisting placemark
        {
            evt.preventDefault();
            if (dragInfo.dragged) { //marker was moved
                db_moveMarker(evt.getTarget().getSnippet(), evt.getLongitude().toFixed(6), evt.getLatitude().toFixed(6));
            }
            else //marker wasn't moved - just clicked on...
            {
                var balloon = ge.createHtmlStringBalloon('');
                balloon.setFeature(evt.getTarget());
                balloon.setMaxWidth(250);
                balloon.setContentString('Care to comment?<br>&nbsp;&nbsp;<textarea rows="2" id="textinput" style="font-family:calibri,verdana,arial;">' + evt.getTarget().getDescription() + '</textarea><br><input style="margin-top:5px;" type="image" src="icons/Save-icon.png" title="Save comment" alt="Save comment" onclick="db_addDesc(\'' + evt.getTarget().getSnippet() + '\',$(\'textinput\').value);" />&nbsp;&nbsp;<input type="image" style="margin-top:5px;"  src="icons/delete-icon.png" alt="Delete Marker" title="Delete Marker" onclick="db_deleteMarker(\'' + evt.getTarget().getSnippet() + '\');" />&nbsp;&nbsp;');
                ge.setBalloon(balloon);
                //$('textinput').focus();  // Note that I tried...
            }
            dragInfo = null; //reset the dragInfo object
        }
    });
}

// Used for the layers control - that doesn't work in IE

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";}
}

// GMaps tab switching function

function switchTab(tab) {
$('tabImg').src=server+"icons/Tab"+tab+".png";

    if (gtab == tab) {
        return false;
    }
    if (tab == 1) {
       $('tab1_markers').style.visibility="visible";
    }
    else if (tab == 2) {
       $('tab2_markers').style.visibility="visible";
    }
    else if (tab == 3){
       $('tab3_markers').style.visibility="visible";
    }
	else if (tab == 4){
       $('tab4_markers').style.visibility="visible";
    }

    if (gtab == 1) {
        $('tab1_markers').style.visibility="hidden";
    }
    else if (gtab == 2) {
      $('tab2_markers').style.visibility="hidden";
    }
	else if (gtab == 3) {
      $('tab3_markers').style.visibility="hidden";
    }
    else {
        $('tab4_markers').style.visibility="hidden";
    }
    gtab = tab;
}

// image mouseover function for GMaps re-center and survey buttons

function swapBtnImg(a,b) {
if(b){
$('btn'+a+'_hover').style.visibility='visible';}
else
{$('btn'+a+'_hover').style.visibility='hidden';}

}

//Callback for marker onmousedown for GMaps

function markerCallback(evt, marker) {
if(mapping){
curMarker=marker;
if(evt.preventDefault){
evt.preventDefault();}
dragging=true;
var url = server+"icons/"+pad(marker)+".png"
myMarker.setImage(url);
myIcon.image=url;
}
else
{ $('modeImage').src="icons/browsingOnly.png";}
}

/////////////////////////////////////////////////////////////////////
/* Marker Management methods */
/////////////////////////////////////////////////////////////////////

function db_addDesc(mrkr, dscr) {

    if (dscr == '') {
        alert('No comment?');
    }
    else {
	info = mrkr.split(":");
	if(ge){
	// Special instructions if in Google Earth mode
        ge.setBalloon(null);
		   // KML
        var c = ge.getFeatures().getFirstChild();
        while (c) {
            var s = c.getNextSibling();
            if (c.getSnippet() == mrkr) {
                c.setDescription(dscr);
                //return false;
            }
            c = s;
        }
		}
		AJAX('include/addDesc.php?cat='+info[0]+'&num='+info[1]+'&dscr='+dscr);
    }
}

function db_moveMarker(mrkr, newLng, newLat) {
//split first arg on colon;
var info = mrkr.split(":");
AJAX("include/movePt.php?cat="+info[0]+'&num='+info[1]+'&x='+newLng+'&y='+newLat);
}

function db_addMarker(mrkr, lng, lat) {
	//split first arg on colon;
	var info = mrkr.split(":");
	if(map.getCurrentMapType().getName()!="Earth"){
	var _z=map.getZoom();}
	else
	{//we're in Earth mode
	var lookAt = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE);
	_z=lookAt.getAltitude();}
	
    AJAX("include/addPt.php?cat="+info[0]+"&num="+info[1]+"&x="+lng+"&y="+lat+"&t="+curType+"&z="+_z);
	
}

function db_deleteMarker(mrkr) {
    var a = confirm("Are you sure you wish to delete this marker?");
    if (a) {
		if(curMode=="GEarth"){
        ge.setBalloon(null);
		    // KML
        var c = ge.getFeatures().getFirstChild();
        while (c) {
            var s = c.getNextSibling();
            if (c.getSnippet() == mrkr) {
                ge.getFeatures().removeChild(c);
            }
            c = s;
        }
        }
		else
		{
		for (i in markerArray)
{
if(markerArray[i].id==mrkr){
map.removeOverlay(markerArray[i]);
}
}
}
		var info = mrkr.split(":");
        AJAX('include/deletePt.php?cat='+info[0]+'&num='+info[1]);
		
		//decrement counter for this category
		markerCount(info[0]);
}
}

function db_GELoadMarker(icon,num,x,y,desc) {
placemark = ge.createPlacemark('');
//placemark.setName(catx[icon]);
placemark.setSnippet(icon+":"+num);
placemark.setDescription(desc);
var _icon_ = ge.createIcon('');
_icon_.setHref(server + "icons/"+pad(icon) + '.png');
var style = ge.createStyle(''); //create a new style
style.getIconStyle().setIcon(_icon_); //apply the icon to the style
style.getIconStyle().getHotSpot().set(0.3, ge.UNITS_FRACTION, 0.3, ge.UNITS_FRACTION);
 style.getIconStyle().setScale(0.8); 
placemark.setStyleSelector(style); //apply the style to the placemark
var point = ge.createPoint('');
point.setLatitude(y);
point.setLongitude(x);
placemark.setGeometry(point);
ge.getFeatures().appendChild(placemark);
}

function db_GMapsLoadMarker(icon,num,x,y,desc)
{
var point = new GLatLng(y,x);

myIcon = new GIcon();
var iconname= server + "icons/"+pad(icon) + '.png';
myIcon.image = iconname;
myIcon.iconSize= new GSize(28,28);
myIcon.iconAnchor = new GPoint(14,14);
myIcon.infoWindowAnchor = new GPoint(16,8);
markerOptions = { icon:myIcon,draggable:true};

if(bIsLoad){
// we need to increment the marker count here based on the marker number
markerHash[parseInt(icon)]++;}

var marker=new GMarker(point,markerOptions);
marker.id =pad(icon)+":"+num+"";
if(mapping){marker.enableDragging();}else{marker.disableDragging();}
markerArray.push(marker);
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+'"';}
	info = marker.id.split(":");
	popUp.innerHTML='<b>'+catx[parseInt(info[0])]+'</b><br><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="#" class="e1" onclick="db_addDesc(\''+marker.id+'\',$(\'txt'+marker.id+'\').value);map.closeInfoWindow();"><img src="http://www.landscapemap2.org/swparks3/images/45.png" border="0" > Save</a>&nbsp;&nbsp;<img src=\'http://www.landscapemap2.org/swparks3/images/splitter.png\'>&nbsp;&nbsp;<a href="#"  onclick="db_deleteMarker(\''+marker.id+'\');"class="e1"><img src="icons/delete-icon.png" border="0"> Delete</a>';

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

GEvent.addListener(marker, "dragstart", function(gll) {
ptOrig.x=gll.lng().toFixed(6);
ptOrig.y=gll.lat().toFixed(6);
});
 
GEvent.addListener(marker, "dragend", function(gll) {
if(gll.lng()>mapBounds.xmin && gll.lng()<mapBounds.xmax && gll.lat()<mapBounds.ymax && gll.lat()>mapBounds.ymin){
db_moveMarker(marker.id,gll.lng().toFixed(6),gll.lat().toFixed(6));
}
else
{
alert('You\'ve moved the marker outside of the study area bounds.');
marker.setLatLng(new GLatLng(ptOrig.y,ptOrig.x));}
        });
}

function db_reloadPts(mode)
{
if(mode=="GMaps"){
//we want to clear all but our master marker overlay
map.clearOverlays();
markerArray=[];
AJAX("include/reloadPts.php?mode=GMaps");
}
else
{
if(ge){
map.clearOverlays();
  var c = ge.getFeatures().getFirstChild();
    while (c) {
        var s = c.getNextSibling();
       if (c.getType() == 'KmlPlacemark') {
            ge.getFeatures().removeChild(c);
       }
        c = s;
    }
			AJAX("include/reloadPts.php?mode=GEarth");
        }
		}
}

//////////////////////////////////////////////////////////////////////////////
/* Form validation for the index.php page */
//////////////////////////////////////////////////////////////////////////////

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();}
}

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='include/checklogin.php?groupID='+a+'&randomID='+b;
//run to the db and check to make sure these values work
AJAX(url);
}

  //used for the consent page
  
function valcheck()
{

{var url='include/consent2.php';
AJAX(url);
}
}
  


//Show or hide the info panel
function ShowHide(item) {
if(item.id=='mrkrDescBox')
{if($('instbox').style.visibility!=='hidden'){opacity('instbox',90,0,100);
if(curMode=="GEarth"){
		destroyNativeHTMLButton();
	}}}
else
{if($('mrkrDescBox').style.visibility!=='hidden'){
opacity('mrkrDescBox',90,0,100);
if(curMode=="GEarth"){
		destroyNativeHTMLButton();
	}
}}
    if (item.style.visibility !== 'hidden') {
    opacity(item.id,90,0,100);
	if(curMode=="GEarth"){
		destroyNativeHTMLButton();
	}
	}
	else 
	{
    opacity(item.id,0,90,0);
	if(curMode=="GEarth"){
	createNativeHTMLButton(379, 16, 701, 477); // x, y, width, height
	}
    }
}

/////////////////////////////////////////////////////////////////////////////////
/* Opacity methods */
/////////////////////////////////////////////////////////////////////////////////

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";}
}


//////////////////////////////////////////////////////////////////////////////////////////////
// AJAX Functions
//////////////////////////////////////////////////////////////////////////////////////////////

  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;
}

/**
 * Helper function for element.addEventListener/attachEvent
 */
function addDomListener(element, eventName, listener) {
  if (element.addEventListener)
    element.addEventListener(eventName, listener, false);
  else if (element.attachEvent)
    element.attachEvent('on' + eventName, listener);
}

/**
 * Helper function to get the rectangle for the given HTML element.
 */
function getElementRect(element) {
  var left = element.offsetLeft;
  var top = element.offsetTop;
  
  var p = element.offsetParent;
  while (p && p != document.body.parentNode) {
    if (isFinite(p.offsetLeft) && isFinite(p.offsetTop)) {
      left += p.offsetLeft;
      top += p.offsetTop;
    }
    
    p = p.offsetParent;
  }
  
  return { left: left, top: top,
           width: element.offsetWidth, height: element.offsetHeight };
}


function destroyNativeHTMLButton()
{
document.body.removeChild($('myIframe'));
document.body.removeChild($('myButton'));
}


/**
 * Create a custom button using the IFRAME shim and CSS sprite technique
 * at the given x, y offset from the top left of the plugin container.
 */
function createNativeHTMLButton(x, y, width, height) {
  // create the button
  var button = document.createElement('a');
  button.href = '#';
  button.className = 'tri-button';
  button.style.display = 'block';
  button.id = 'myButton';
  //button.style.backgroundImage = 'url(btn_html.png)';
  button.style.backgroundColor = 'white';
  
  // create an IFRAME shim for the button
  var iframeShim = document.createElement('iframe');
  iframeShim.frameBorder = 0;
  iframeShim.scrolling = 'no';
  iframeShim.id='myIframe';

  iframeShim.src = (navigator.userAgent.indexOf('MSIE 6') >= 0) ?
      '' : 'javascript:void(0);';

  // position the button and IFRAME shim
  var pluginRect = getElementRect(document.getElementById('map3d'));
  button.style.position = iframeShim.style.position = 'absolute';
  button.style.left = iframeShim.style.left = (pluginRect.left + x) + 'px';
  button.style.top = iframeShim.style.top = (pluginRect.top + y) + 'px';
  button.style.width = iframeShim.style.width = width + 'px';
  button.style.height = iframeShim.style.height = height + 'px';
  
  // set up z-orders
  button.style.zIndex = 10;
  iframeShim.style.zIndex = button.style.zIndex - 1;
  
  // set up click handler
  addDomListener(button, 'click', function(evt) {
    alert('You clicked the native HTML button!');
    
    if (evt.preventDefault) {
      evt.preventDefault();
      evt.stopPropagation();
    }
    return false;
  });
  
  // add the iframe shim and button
  document.body.appendChild(button);
  document.body.appendChild(iframeShim);
}

//used to add/remove layers from the map
function _KML(item)
{
if(item.checked) //turning on a layer
  {
    switch(item.id)
      {
      case "boundary":
      map.addOverlay(geoBound);
      break;
	  case "parks":
     map.addOverlay(geoParks);
      break;
	  case "photos":
	  geoPhotos.show();
      break;
      }
  }
if(!item.checked) //turning off a layer
  {
    switch(item.id)
      {
      case "boundary":
      map.removeOverlay(geoBound);
      break;
	  case "parks":
     map.removeOverlay(geoParks);
      break;
	  case "photos":
	  geoPhotos.hide();
      break;
      }
  }
}
function popMrkrList()
{
var strContent = '<div style="padding-top:5px;font-size:13px;"><b>Common Experiences</b><br></div>';
for (i=0;i<numMarkers;i++){
if (i==10){strContent += '<div style="padding-top:5px;font-size:13px;"><b>Track-based and Passive</b><br></div>';}
if(i==21){strContent += '<div style="padding-top:5px;font-size:13px;"><b>Adventure experiences</b><br></div>';}
if(i==34){strContent += '<div style="padding-top:5px;font-size:13px;"><b>Values and impacts</b><br></div>';}
strContent += "<div onclick='mrkrDescFill("+i+");' onmouseover='this.style.cursor=&#34;pointer&#34;;this.style.backgroundColor=&#34;#e4ebfd&#34;;this.style.border=&#34;1px solid #999&#34;;' onmouseout='this.style.backgroundColor=&#34;#fff&#34;;this.style.cursor=&#34;#333&#34;;this.style.border=&#34;1px solid #DDD&#34;;' style='margin-right:10px;margin-top:11px;margin-bottom:9px;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #DDD;padding:4px 0px 4px 2px;font-size:13px;'><img src='" + server + "icons/" + pad(i) + ".png' align='left'> " + catx[i] + "</div>";
}
$('mrkrList').innerHTML = strContent;
}

function mrkrDescFill(intMrkrNum){

$('mrkrDescList').innerHTML = "<b>" + catx[intMrkrNum] + "</b><br><br>" + mrkrDesc[intMrkrNum];
}
function checkPtr(item){
if(gtab==1){
if(parseInt(item.id.replace("mrkrDiv",""))<10){item.style.cursor='pointer';}
else{item.style.cursor='';}
}
else if(gtab==2){
if(parseInt(item.id.replace("mrkrDiv",""))<11){item.style.cursor='pointer';}
else{item.style.cursor='';}
}
else
{item.style.cursor='pointer';}
}

function markerDesc(intDivNum){
//take the div number and the tab and somehow deduce which marker that is.
if (gtab==1){
$('mrkrDescList').innerHTML = "<b>" + catx[intDivNum] + "</b><br><br>" + mrkrDesc[intDivNum];
}
else if (gtab==2){
$('mrkrDescList').innerHTML = "<b>" + catx[intDivNum+10] + "</b><br><br>" + mrkrDesc[intDivNum+9];
}
else if(gtab==3){
$('mrkrDescList').innerHTML = "<b>" + catx[intDivNum+21] + "</b><br><br>" + mrkrDesc[intDivNum+21];
}
else if(gtab==4){
$('mrkrDescList').innerHTML = "<b>" + catx[intDivNum+34] + "</b><br><br>" + mrkrDesc[intDivNum+34];
}
if($('mrkrDescBox').style.visibility=='hidden'){ShowHide($('mrkrDescBox'));}
}

