/**code for GCOLE, Started August 2009.  Author: Paul Van Deusen
**/
var centerLatitude = 40; //initial center coordinates
var centerLongitude = -96.;
var startZoom = 4; //initial zoom level
var map;
var state; //state centroid data
var county; //county centroid data
var stMarker;
var ctMarker; //county markers
var nIconBlue;
var nIconGreen;
var cIconBlue;
var cIconGreen;
var ncasiIcon=new Array(); //marker icons to show on the map
var radioVal='s'; //data selection method, s,c or r
var dataLocale; //location of the user's Rdata file
var layerSelected="none"; //GCOLE GIS layer
var circleLat; //user selected circle
var circleLon;
var isGCOLEdata=false; //is the user selected data current 
var selectedQuanVar=[]; //holds quan vars in order selected;
var selectedQualVar=[]; //qual vars in order selected;

function init() {
    if (GBrowserIsCompatible()) {
        map = new google.maps.Map2(document.getElementById("map"));
	 map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        map.disableDoubleClickZoom();
        map.addMapType(G_PHYSICAL_MAP);
	map.addControl(new PromoControl("/"));
        //map.addControl(new PromoControl2("/"));
        GEvent.addListener(map,"dblclick",function(overlay,latlng){
			     getCircle(latlng); });
        GEvent.addListener(map,"maptypechanged",function(){
	    changeLayer(); });
       	jQuery.get("censusData/state.csv", setStateData);
        jQuery.get("censusData/cnty.csv", setCntyData);
        ncasiTiles();
	resetMap();
        clearMap();
        
	 $("#map").fadeOut("fast");
       $('#overlay').fadeOut(2000, function () {
           $("#map").fadeIn("fast");
           $("#overlay").remove();
       });

        adjustSize('0');
}
}

//called when user hits reset on variables tab
function resetQVars(){
 selectedQuanVar=[]; //holds quan vars in order selected;
 selectedQualVar=[]; 
 var where = document.getElementById("qualVars");
      where.innerHTML="<b>Qualitative Vars: </b>";
     where = document.getElementById("quanVars");
      where.innerHTML="<b>Quantitative Vars: </b>";
}


//analysis  variable selection changed
//keeps track of the order of selection
function analysisVarChange(type){
  var qVar=[];
  var varList;
  if(type=="cvar"){
    qVar=selectedQualVar; varList=document.variablesForm.cvar;}
  if(type=="yvar"){
    qVar=selectedQuanVar; varList=document.variablesForm.yvar;}
 
   if(varList.selectedIndex==-1){qVar=[]; return;} //clear list

  //remove any vars that are no longer selected
    for(var i=0;i<varList.options.length;i++){
        var name=varList.options[i].value;
	if(!varList.options[i].selected)
         for(var j=0;j<qVar.length;j++)
            if(name==qVar[j]) qVar.splice(j,1); //this no longer selected
    }

  //add selected vars not already in the list
    for(var j=0;j<varList.options.length;j++){
      if(varList.options[j].selected){
          var name=varList.options[j].value;
	if(qVar.join(',').indexOf(name)==-1)
            qVar.push(name); 
     }
    }
    if(type=="cvar"){ selectedQualVar=qVar;
      var where = document.getElementById("qualVars");
      where.innerHTML="<b>Qualitative Vars: </b>"+qVar.join(", ");
    }
    if(type=="yvar"){selectedQuanVar=qVar;
      var where = document.getElementById("quanVars");
      where.innerHTML="<b>Quantitative Vars: </b>"+qVar.join(", ");
    }
}

//called when user dble clicks or changes radius.
function getCircle(latlng){
  radioVal = $("input[name='radio_data']:checked").val();
  if(radioVal!='r')return;
  isGCOLEdata=false;
  var dec=100000;
  circleLat=Math.round(latlng.lat()*dec)/dec;
  circleLon=Math.round(latlng.lng()*dec)/dec;
  $("#myConsole").html("<b>Lat="+circleLat+", Lon="+circleLon+"</b>");
   map.clearOverlays();
  //draw the circle
   var radius = $('[name=selectNum]').val();; //user defined radius
   drawCircle(latlng,radius,40,"#FF6633");//"#33FF99"
}

function changeRadius(){
  radioVal = $("input[name='radio_data']:checked").val();
  if(radioVal!='r')return;
  isGCOLEdata=false;
  map.clearOverlays();
  if(circleLat==undefined){
    alert("Double click map at circle center"); return;
  }
  var latlng=new GLatLng(circleLat,circleLon);
  //draw the circle
   var radius = $('[name=selectNum]').val();; //user defined radius
   drawCircle(latlng,radius,40,"#FF6633");//"#33FF99"
}

function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{
  // Esa 2006
  //calculating km/degree
  var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
  var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

  //Loop 
  var points = [];
  var step = parseInt(360/nodes)||10;
  for(var i=0; i<=360; i+=step)
    {
      var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + 
			     (radius/lngConv * Math.sin(i * Math.PI/180)));
      points.push(pint);
    }
  fillColor = fillColor||liColor||"#0055ff";
  liWidth = liWidth||2;
  var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
  map.addOverlay(poly);
}


//get data for state centroids
function setStateData(data){
  state=csv2json(data);
  makeStateMarkers(state);
}

//get data for county centroids
function setCntyData(data){
  county=csv2json(data);
  makeCntyMarkers(county);
}

//turn csv data into json object.use $.get to load data
//array is returned.  Access row j var1 as result[j].var1
function csv2json(data){ 
 
  var result=[]; //will hold the csv converted to json array
  var sep='\n'; //the line separator in the server response
  var vSep=',';  //variable separator;
  
  try{
    var rows=data.split(sep); data=[]; //original rows in source data
    names=rows[0].split(vSep); //row 1 is variable names;
     var json; //temp var to hold each row as it is converted
      
     for(var i=1;i<rows.length-1;i++){
       json="({";
       var line=rows[i].split(vSep);
      for(var j=0;j<names.length;j++){
	//handle nonnumeric data in json by adding quotes
        if(line[j]*1==line[j]) json+=names[j]+": "+ line[j]; else
           json+=names[j]+": '"+ line[j] +"'" ;
       if(j<names.length-1)json+=",";
      }
      json+="})";
    json=eval(json);
     result.push(json);
    }  
     //alert(result.length);
  }catch(err){alert("row i, csv2json error: "+i+","+err);}
  return result;
}

function makeStateMarkers(state){
  makeIcons();
   nIconBlue=ncasiIcon[0];
   nIconGreen=ncasiIcon[1];
  
  stMarker=[];  
  for (var i = 0; i < state.length; i++) {
    stMarker[i]=makeAnStMarker(i,false,nIconBlue);
  map.addOverlay(stMarker[i]);
}
}

//make a state marker
//i=the index in the stMarker array
//selected indicates if the user selected this state
function makeAnStMarker(i,selected,nIcon){
   var point = new GLatLng(state[i].LAT,state[i].LON);
    var marker = new GMarker(point,{title: state[i].ST, icon:nIcon});
   marker.selected=selected;
   marker.number=i;
    GEvent.addListener(marker, 'click',
        function() {
			 this.selected=!this.selected;
                         changeStMarkerStatus(this.number,this.selected); 
                         if(this.selected)map.panTo(this.getLatLng()); 
                 }
    );
    return marker;
}


function changeStMarkerStatus(i, selected){
  if ( stMarker[i] ) {
     map.removeOverlay(stMarker[i])
    if(selected)nIcon=nIconGreen; else nIcon=nIconBlue;
     stMarker[i] = makeAnStMarker(i,selected,nIcon);
    map.addOverlay(stMarker[i]);
    isGCOLEdata=false;
  }
}


function makeCntyMarkers(state){
  cIconBlue=ncasiIcon[2];
  cIconGreen=ncasiIcon[3];
  
  ctMarker=[];  
  for (var i = 0; i < county.length; i++) {
    ctMarker[i]=makeAnCtMarker(i,false,cIconBlue);
    // map.addOverlay(ctMarker[i]);
}
}

//make a county marker
//i=the index in the ctMarker array
//selected indicates if the user selected this state
function makeAnCtMarker(i,selected,cIcon){
   var point = new GLatLng(county[i].LAT,county[i].LON);
    var marker = new GMarker(point,{title: county[i].NAME+","+county[i].ST, icon:cIcon});
   marker.selected=selected;
   marker.number=i;
    GEvent.addListener(marker, 'click',
        function() {
			 this.selected=!this.selected;
                         changeCtMarkerStatus(this.number,this.selected); 
                 }
    );
    return marker;
}

function changeCtMarkerStatus(i, selected){
  if ( ctMarker[i] ) {
     map.removeOverlay(ctMarker[i])
    if(selected)nIcon=cIconGreen; else nIcon=cIconBlue;
     ctMarker[i] = makeAnCtMarker(i,selected,nIcon);
    map.addOverlay(ctMarker[i]);
    isGCOLEdata=false;
  }
}



function makeIcons(){
  var images=new Array("blueSpruce","greenSpruce","blueHwd","greenHwd");
   var shadowImage="/google/icons/shadowSmall.gif";
  
    for( i=0; i<images.length; i++){
      var icon = new GIcon();
       icon.image="/google/icons/"+images[i]+"Icon.gif";
       //icon.shadow=shadowImage;
       //icon.shadowSize=new GSize(25,25);
       icon.iconSize=new GSize(16,25);
       icon.iconAnchor = new GPoint(8,25);
       icon.infoWindowAnchor = new GPoint(8,13);       
       ncasiIcon[i]=icon;     
      
    }
}





//go to alaska
function toAlaska(){
  clearMap();
 map.setZoom(startZoom);
 map.panTo(new GLatLng(63,-141));
}

//put the map back to an initial state
function resetMap(){
  $('input[name="radio_data"]')[0].checked = true;
   radioVal='s';
   $('[name=selectGIS]').val('None'); //no gis layers at init
   layerSelected="None";
  $('#stateCnty').attr('disabled', true); //disable county selection on init
  $('#tabs').tabs('select', 0); // switch to first tab

   clearMap();
   map.setMapType(G_PHYSICAL_MAP); //going to physical map inits GCOLE layers
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
}

function clearMap(){
  isGCOLEdata=false;
  if(county!=undefined)makeCntyMarkers(county); //clears any selections
  map.clearOverlays();
  $('#tabs').data('disabled.tabs', [1, 2, 3, 4, 5]);
  circleLat=null; circleLon=null;
  $("#myConsole").html("Begin by selecting a state or defining a circle.");
  if (state!=undefined && radioVal!='r') makeStateMarkers(state);
  clearRegionCheckBoxes();
}

//get the data while on tab1
function getData(){
  radioVal = $("input[name='radio_data']:checked").val();
  var statesSelected=""; 
  var countiesSelected="";
  var theData="";
  if(radioVal=='s' || radioVal=='c'){
    for (var i = 0; i < state.length; i++) {//what states were selected
      if(!stMarker[i].selected)continue;
      var stcd=state[i].STATECD;
      if((stcd*1)<10)stcd='0'+stcd;
      statesSelected+=stcd+"X";
    }
    if(statesSelected.length==0){alert("Please select a state");return;}
     theData="states="+statesSelected;
  }

      if(radioVal=='c'){ //what counties were selected
        for(var j=0; j<county.length; j++)
	  if(ctMarker[j].selected){
            var fips=1000*county[j].STATECD + 1*county[j].COUNTYCD+1000000;
            countiesSelected+=fips+"X";
	  }
      if(countiesSelected.length==0)
              {alert("Please select some counties");return;}
      theData+='&'+"counties="+countiesSelected;
      }

      if(radioVal=='r'){//selecting data in a circle
         if(circleLat==undefined){
	   alert("Please define a selection circle"); return;
	 }
       var radius=$('[name=selectNum]').val();
       theData="radius="+radius+"&lat="+circleLat+"&lon="+circleLon;
      }
   
      if(theData.length==0){alert("Error in gcole.getData()"); return;}

    $("#myConsole").load("html/working0.html");
 var url="/cgi-bin/RCOLE/R.cgi/RstateRetrieval.R";
   $.ajax({
   type: "POST",
   url: url,
   data: theData,
   success: function(msg){
         $("#myConsole").html("Data complete");
	 dataLocale=msg.substring(5,msg.length-2);
	 if(msg.length>1){
	   //alert("Data Locale:" + dataLocale);
	   isGCOLEdata=true;
	      alert("Now you can select another tab");
             $('#tabs').data('disabled.tabs', [3,4]);   
	  } 
	 else {alert("getData error"); isGCOLEdata=false;}
   }
 });

 
}

//submit the job after getting data
//type indicates the tab is came from and sendType = normal or email
function submitRjob(type,sendType){
  if(!isGCOLEdata){
    alert("You may not have the correct data. \nPress the 'getData' Button on the 'Select Data' tab again");
    return;
  }
  if(type=='tables'){
   var script=$('[name=script]').val();
   if(!script){alert("Select an analysis option"); return;}
  }
 if(type=='maps'){
   var script=$('[name=mapScript]').val();
   if(!script){alert("Select a mapping option"); return;}
  }
 if(type=='reports'){
   var script=$('[name=reportScript]').val();
   if(!script){alert("Select a report option"); return;}
  }
 var url='/cgi-bin/RCOLE/R.cgi/'+script;
   var params='data='+dataLocale;
   var filters=$("#filtersForm").serialize();
   filters=formatFilters(filters);//COLE scripts need special format

 if(filters.length>1) params+='&filter='+filters;
   var variables='yvar='+selectedQuanVar.join('&yvar=') + '&cvar='+selectedQualVar.join('&cvar=');

   if(type!='reports' && (selectedQuanVar.length==0 || selectedQualVar.length==0)){
     alert("You must select Quantitative and Qualitative variables"); return;
   }
   if(variables.length>1)params+='&'+variables;
   //alert("url="+url+" params="+params);
  

   if(sendType=='email'){
     submitEmailJob(url,params);
     return;
   }

  $("#myConsole").load("html/working0.html");

 $.ajax({
   type: "POST",
   url: url,
       data: params,
   success: showJob
 });

}

//open a help window to show results of R Rscript analysis
function showJob(msg){
    $("#myConsole").html("Query complete");
    var win=window.open(); //IE is sensitive to changes in this.
  win.document.write(msg);
  win.document.close();
    win.focus();
 }

function submitEmailJob(Rscript,pars){
  
  var address=getEmailAddress();
  var url = '/cgi-bin/GCOLE/GncasiMail.pl';
  while(pars.indexOf('&')>0) pars=pars.replace('&','$$$');
  while(pars.indexOf('=')>0) pars=pars.replace('=','->');
  pars='url='+Rscript+'$$$'+pars;
  pars+='&to='+address+'&subject=Analysis results from GCOLE';
  // alert("submitEmail url: "+url+" pars: "+pars);
  
$.ajax({
   type: "GET",
   url: url,
       data: pars,
   success: showJob
 });

  $('#myConsole').html="Email submitted";

}

//this gets the email address and makes all email fields match
function getEmailAddress(){
  var currentTab = $('#tabs').tabs('option', 'selected');
  var t3=document.tablesForm.email.value;
  var t4=document.mapsForm.email.value;
  var t5=document.reportsForm.email.value;
  var email=t3;

  if(currentTab==4)email=t4;
  if(currentTab==5)email=t5;

   document.tablesForm.email.value=email;
   document.mapsForm.email.value=email;
   document.reportsForm.email.value=email;
   if(!((email.indexOf(".") > 2) && (email.indexOf("@") > 0)))
                    alert("Please enter a valid email address.");
  return(email);
}

//put the filters into the format that the COLE scripts require
function formatFilters(filters){
  if(filters.length<2)return('0');
 var result="";
 var prev="";
 filters=filters.split("filter=");
 for(var i=1;i<filters.length;i++){
   var ff=filters[i].split(")");
   var fname=ff[0];
   var fcode=ff[1];
   fcode=fcode.replace("&","");
   if(i==1){result=fname+" "+fcode; prev=fname; continue;}
   if(fname==prev)result+=" "+fcode; //more codes for same filter
   else {prev=fname; result+=")"+fname+" "+fcode}; //next filter
 }
 //alert(" result: "+result); 
 return(result);
}

//set things up for county selection after user presses getCounties button
function prepCounty(){
  var isState=false;
  var cntyZoom=6;
for (var i = 0; i < state.length; i++) 
  if(stMarker[i].selected){
      isState=true; 
      if(state[i].STATECD==2)cntyZoom=5; //Alaska needs less zoom
      break;
   }
 if(!isState){ alert("Select a state first"); return;}
  map.clearOverlays();
  map.setZoom(cntyZoom);
  layerSelected=county;
  $('[name=selectGIS]').val('county');
  changeLayer();

  var isAll=$('#allCounties').attr('checked'); //should all cntys be selected?
  for (var i = 0; i < state.length; i++){ 
   if(stMarker[i].selected){
     for(var j=0; j<county.length; j++)
       if(state[i].STATECD==county[j].STATECD){
	 ctMarker[j].selected=isAll;
        changeCtMarkerStatus(j, isAll)
      }
   }
  }
}

//user changed data selection option
//val =s for state, c for county, r for radius
function changeSelected(val){
  isGCOLEdata=false;
  var isCnty=false;
  circleLat=null;circleLon=null;
  if(val=='c')isCnty=true;
 $('#stateCnty').attr('disabled', !isCnty);
    map.clearOverlays();
    clearRegionCheckBoxes();
   if(val=='r')changeRadius();
 
 if(val!='r')makeStateMarkers(state);
   
}

//uncheck the regional checkboxes
function clearRegionCheckBoxes(){
 $('input[name=region-PNW]').attr('checked', false);
 $('input[name=region-Int-W]').attr('checked', false);
 $('input[name=region-NC]').attr('checked', false);
 $('input[name=region-S]').attr('checked', false);
 $('input[name=region-NE]').attr('checked', false);
}

//user selected states in a region
function regionSelected(val){
   if(!($("input[name='radio_data']:checked").val()=='s')){ 
        alert("Can only select regions when the State button is checked");
	clearRegionCheckBoxes();
        return;
   }
  var region=[];
  if(val=='PNW')region=[06,41,53];
  if(val=='Int-W')region=[4,8,16,30,32,35,49,56];
  if(val=='NC')region=	[17,18,19,20,26,27,29,31,38,46,55];
  if(val=='S')region=  [1,5,12,13,21,22,28,37,40,45,47,48,51];
  if(val=='NE')region=[9,10,23,24,25,33,34,36,39,42,44,50,54];

  var N=0,LAT=0,LON=0;
for (var r=0;r<region.length;r++){
 for (var i = 0; i < state.length; i++) {//what states were selected
   if(state[i].STATECD==region[r]){//toggle the selection
    changeStMarkerStatus(i, !stMarker[i].selected);
    if(stMarker[i].selected){N++;LAT+=state[i].LAT;LON+=state[i].LON;}
    break;
  }
 }

 if(N>=1)map.panTo(new GLatLng(LAT/N,LON/N)); 
}
 
}//end regionSelected function

//this is called by the $(document).ready function in tabs.shml
function jQueryInit(){

  $('#tabs').bind('tabsselect', function(event, ui) {
      //enable all tabs after user visits variables tab
      if(ui.index==2){$('#tabs').data('disabled.tabs',[]);
    } 
     
  });

}

//set up the  tabs. This makes  ajax requests to  perl scripts
//called from tabs.shtml
function initGColeTabs(){
  var  url="/cgi-bin/GCOLE/tabs/GFilters.pl";
  $("#gcoleFilters").load(url);
       url="/cgi-bin/GCOLE/tabs/GVariables.pl";
  $("#gcoleVariables").load(url);
      url="/cgi-bin/GCOLE/tabs/GAnalysis.pl";
  $("#gcoleAnalysis").load(url);    
       url="/cgi-bin/GCOLE/tabs/GMaps.pl";
  $("#gcoleMaps").load(url);
       url="/cgi-bin/GCOLE/tabs/GReports.pl";
  $("#gcoleReports").load(url);
 $('#tabs').data('disabled.tabs', [1, 2, 3, 4, 5]);
 if($("input[name='radio_advanced']:checked").val()=='r'){
   //remove analysis and maps tab as the default
     $("li:contains('Analysis')").hide();
    $("li:contains('Maps')").hide();
    $("li:contains('Variables')").hide();
 }
}

function changeTabs(type){
  if(type=="a"){ 
    $( "li:hidden" ).show();
  }
  if(type=="r"){
   //remove analysis and maps tab as the default
    $("li:contains('Analysis')").hide();
    $("li:contains('Maps')").hide();
    $("li:contains('Variables')").hide();
  }
  
}

//open a help window.  This uses the COLE help files for the
//analysis and map functions.  
//@param name - who called this function
function showHelp(location){
  var url=location;

  if(location=="variables")url="/COLE/help/variableTabHelp.html";
  if(location=="reports"){
     var script=$('[name=reportScript]').val();
   if(!script){url="help/genericSubmitHelp.html"}
   else url="/COLE/help/reportTabHelp.html"
  }
   if(location=="analysis"){
     var script=$('[name=script]').val();
   if(!script){url="help/genericSubmitHelp.html"}
   else url="/COLE/help/"+script.replace(".R",".html");
  }
  if(location=="maps"){
     var script=$('[name=mapScript]').val();
   if(!script){url="help/genericSubmitHelp.html"}
   else url="/COLE/help/"+script.replace(".R",".html");
  }

  var width=640;
  var specs="width="+width+",height=640,resizable=yes,toolbar=no,location=no,menubar=no,scrollbars=yes,left=640,top=10";
  var win=window.open(url,"Help",specs);
  win.focus();
}


//change the size of the map and control divs
function adjustSize(size){
  //alert("size="+size+" screen width="+screen.width+" screen height="+screen.height);
  if(size==0 && screen.width>=1200)size='+';//done at init
  var fac=1.0;
  if(size=='+')fac=1.1;
  else if(size=='-')fac=1/1.1;

  //map div
  var m=document.getElementById("map").style;
  var width=m.width.substring(0,m.width.length-2);
    var left=Math.round(width*fac) + 10;//left edge of control div
   m.width=Math.round(width*fac) +'px';
  var height=m.height.substring(0,m.height.length-2);
   m.height=Math.round(height*fac) +'px';
  //control div
  var c=document.getElementById("control").style;
  width=c.width.substring(0,c.width.length-2);
   if(width>400)width=400;
  c.width=Math.round(width*fac) +'px';
  height=c.height.substring(0,c.height.length-2)*fac;
   c.height=Math.round(height) +'px';
    c.left=left +'px';
  //adjust tab contents size
  document.getElementById("gcoleFilters").style.height=Math.round(height*.7) +'px';
  document.getElementById("gcoleVariables").style.height=Math.round(height*.6) +'px'; 
   document.getElementById("gcoleAnalysis").style.height=Math.round(height*.3) +'px';
   document.getElementById("gcoleMaps").style.height=Math.round(height*.5) +'px'; 
   document.getElementById("gcoleReports").style.height=Math.round(height*.175) +'px'; 

  map.checkResize();
}


//user changed the GForest layer
function changeLayer(){
  var cForm=document.selectByForm;//points to the control form
 layerSelected=cForm.selectGIS.options[cForm.selectGIS.selectedIndex].value;
 //alert("gis="+layerSelected);
 if(layerSelected!="none" && map.getZoom()<5)map.setZoom(5);
   map.setCenter(map.getCenter());//refresh map without user noticing

   showKey();
}

//show the color key for the current GForest map layer
function showKey(){
  var console = document.getElementById("myConsole");
  console.innerHTML="Select 'None' to clear GIS layers. <br> Select GCOLE on Google Map to see only GCOLE layer.";
 if(layerSelected=="plots")
   console.innerHTML="<img src='/google/help/LGDplots.jpg' alt='key'>";
if(layerSelected=="ecoFs")
   console.innerHTML="<br><font size='6'><a href='/google/help/Legend_ecoFS.pdf'>Ecological Section Key</a></font><br> <br>";
if(layerSelected=="change")
  console.innerHTML="<img src='/google/help/LandUseKey.jpg' alt='key'>";
if(layerSelected=="nlcd01")
  console.innerHTML="<img src='/google/help/LGDnlcd01.gif' alt='key'>";
if(layerSelected=="ned")
  console.innerHTML="<img src='/google/help/LGDned.jpg' alt='key'>";
}


///set up forest tile layer
///go to the plotTab.html file to add more to html form
function ForestGetTileUrl(a,z) {	
  //var f="/cgi-bin/google/tile.sh?"+"x="+a.x+"&y="+a.y+"&zoom="+z;
  var xDir=Math.floor(a.x/50)*50;
  var f="";
  if(layerSelected=="plots")
   f="/google/tiles/z"+z+"/XYfia/"+xDir+"/XYfia"+a.x+"_"+a.y+"_"+z+".gif";
  if(layerSelected=="county")
   f="/google/tiles/z"+z+"/gcnty/"+xDir+"/gcnty"+a.x+"_"+a.y+"_"+z+".gif";
  if(layerSelected=="ecoFs")
   f="/google/tiles/z"+z+"/ecoFs/"+xDir+"/ecoFs"+a.x+"_"+a.y+"_"+z+".gif";
  if(layerSelected=="change")
    f="/google/tiles/z"+z+"/chg/"+xDir+"/chg"+a.x+"_"+a.y+"_"+z+".gif";
   if(layerSelected=="nlcd01")
   f="/google/tiles/z"+z+"/nlcd01/"+xDir+"/nlcd01"+a.x+"_"+a.y+"_"+z+".gif";
   if(layerSelected=="ned")
   f="/google/tiles/z"+z+"/ned/"+xDir+"/ned"+a.x+"_"+a.y+"_"+z+".gif";

  return f;
} 

function ncasiTiles(){
var copyCollection = new GCopyrightCollection('');
 forestLayer = new GTileLayer(copyCollection);

 forestLayer.getTileUrl = ForestGetTileUrl;
 forestLayer.isPng=function(){return false;} 
 forestLayer.getOpacity = function() {return 0.5;}
 
 //add forest layers
 forestMapLayers=G_HYBRID_MAP.getTileLayers();
 forestMapLayers.push(forestLayer); 
 forestMapLayers=G_SATELLITE_MAP.getTileLayers();
 forestMapLayers.push(forestLayer);
 forestMapLayers=G_NORMAL_MAP.getTileLayers();
 forestMapLayers.push(forestLayer);
 forestMapLayers=G_PHYSICAL_MAP.getTileLayers();
 forestMapLayers.push(forestLayer);
 
 
 //add code to made the gforest button and layer
 var copyCollection2 = new GCopyrightCollection('GCOLE');
  var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "&copy 2009 GCOLE");
copyCollection2.addCopyright(copyright);

 var forestlayer = [new GTileLayer(copyCollection2, 5, 13)];

  forestlayer[0].getTileUrl = ForestGetTileUrl;
  var forestmap = new GMapType(forestlayer, new GMercatorProjection(14), "GCOLE", {errorMessage:"GCOLE data unavailable"});
  map.addMapType(forestmap);

}



//get rid of global variables and call GUnload
function gcoleUnload(){
  GUnload();
}

window.onload = init;
window.onunload = gcoleUnload;

