/**code for GFOREST.  Started in 11/06.  Author: Paul Van Deusen
NCASI.
**/

var centerLatitude = 40; //initial center coordinates
var centerLongitude = -96.;
var startZoom = 4; //initial zoom level
var markerChangeZoom=4; //zooms at this level and above get larger markers
var map;
var my_Markers=new Array(); //hold all the marker data
var ncasi_urlAnim=""; //url for 3d animated graph
var ncasi_url3d=""; //set when an infoWindow opens for a marker
var ncasi_urlGrow=""; //url for animated growth image
var ncasi_urlTree=""; //set to the currently selected plot id;
var winNcasi_Anim; //animated gif window
var winNcasi_3d; //3d graph window
var winNcasi_grow;//3d growth window
var winNcasi_Tree; //tree list window
var query=[]; //stored queries
var query_time=null;
var GRandomDataFileName=1; //store data here for analysis
var isGForestData=false; //indicates if data are ready for analysis scripts
var isGForestSubmitOK=true; //don't submit something multiple times
var isGForestAreaSubmitOK=true; //don't submit something multiple times
var mySecret="none"; //this starts out as a password from the user
var layerSelected="forest"; //GForest Map layer
var dataType="none"; //indicates what kind of data the user wants
var submitTab=0; //indicates the tab the user was on when a job is submitted;
var selectedQuanVar=[]; //holds quan vars in order selected;
var selectedQualVar=[]; //qual vars in order selected;

//login allows the user to enter a password to see more information
function userLogin(){
  loginWin=window.open("html/pwd.html","login","width=400,height=150,resizable=yes,toolbar=no,location=no,menubar=no,scrollbars=yes,left=300,top=300");
  loginWin.focus();
}
function checkPassword(){
  if(loginWin && loginWin.open && !loginWin.closed){
    var loginForm=loginWin.document.form1;
    mySecret=loginForm.pwd.value;
    mySecret=TEAencrypt("Inside the ncasi firewall", mySecret)
    loginWin.close();
  }
 
if(mySecret!=theKey && mySecret!=theKey2 && mySecret!=theTempKey){
    alert("GForest Report Permission Denied: Incorrect Password");
  }
 
}

//set up the  tabs. This makes  ajax requests to  perl scripts
//called from tabs.shtml
function initGForestTabs(){

  var  url="/cgi-bin/google/tabs/GFilters.pl";
  $("#GForestFilters").load(url);
       url="/cgi-bin/google/tabs/GVariables.pl";
  $("#GForestVariables").load(url);
      url="/cgi-bin/google/tabs/GTables.pl";
  $("#gforestTables").load(url);    
       url="/cgi-bin/google/tabs/GMaps.pl";
  $("#gforestMaps").load(url);
       url="/cgi-bin/google/tabs/GReports.pl";
  $("#gforestReports").load(url);

}

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

function getCurrentTab(){return($('#tabs').tabs('option', 'selected')+1);}

//store the queries in a JSON array so they can all be sent to the
//server at once
function getQuery(latlng){
  // alert(latlng.lat()+" "+latlng.lng()); return;
  if(getCurrentTab()==7){draw(latlng);return;}//came from SIM tab
  clearTimeout(query_time);
  var cForm=document.forms[0];//points to the control form
  var num=cForm.selectNum.options[cForm.selectNum.selectedIndex].value;
  var nTypes=4; //n of selection types, e.g. state,county,etc
  for(var i=0;i<nTypes;i++)
    if(cForm.radio_button[i].checked)type=cForm.radio_button[i].value;
  var q1=eval([{"Lat":latlng.lat(), "Lon":latlng.lng(), "Type":type, "Num":num }]);
  query.push(q1[0]);
  if(isGForestSubmitOK && cForm.GForestDelay.checked){ 
    document.getElementById("temp").innerHTML="Reset Delay";
    $("#temp").load("html/cache.html"); //show gif
   query_time=setTimeout('getData("MapQuery")',4000);} else {
    document.getElementById("temp").innerHTML="Delay is off";
    getData("MapQuery");
  }
  
}

//this gets the data from the server with an Ajax request
//the Ajax results go to the getMarker function
//@pars caller - who called this function
function getData(caller){
  if(query.length==0){
    alert("Select some data first? Suggestion: Double Click the map.");
    return;
  }

  var onCompleteFunction=getMarkers;
  if(submitTab==7){
    onCompleteFunction=simJobPrep;
    if(caller=="simEmail")onCompleteFunction=simJobEmailPrep;
     caller="MapQuery";
  }


  isGForestData=false; 
  var suffix=0;
  if(!isGForestSubmitOK){
      if(caller=="MapQuery") var dum=query.pop(); //don't keep this query
    suffix=1;
  }

  var filters="";
  if(caller=="FilterQuery"){
    isGForestData=true; //data are prepped for a filters query
    filters=formatFilters();
    if(filters.length<2){
      alert("No filters: Will still submit query. Suggestion: Select some filters.");
      caller="MapQuery";
      isGForestData=false;
    }
  }

var url = '/cgi-bin/google/R.cgi/GForest'+caller+'.R';
    var cForm=document.forms[0];//points to the control form
    var max=cForm.selectMax.options[cForm.selectMax.selectedIndex].value;
    var pars='Max='+max;
  for(var i=0;i<query.length;i++)
    pars+='&Lat='+query[i].Lat+'&Lon='+query[i].Lon+'&Type='+query[i].Type+'&Num='+query[i].Num;
  if(filters.length>0)pars+="&filter="+filters; //add the filter selections
  pars+="&data="+GRandomDataFileName; //unique file name for this user

  //dont show markers if on sim tab, getMarkers will call submitRjob

  if(isGForestSubmitOK){ //don't submit multiple times
      isGForestSubmitOK=false;
     
      $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: onCompleteFunction
      });
  }
 var workURL="html/working"+suffix+".html";
  $("#temp").load(workURL);
 if(suffix==1)setTimeout('readyForNextSubmit()',5000);
}


//this makes sure the "wait a minute" animated gif wont run forever.
//only needed with slow Internet connections.
function readyForNextSubmit(){
    if(!isGForestSubmitOK)setTimeout('readyForNextSubmit()',3000);
     document.getElementById("temp").innerHTML=", <h3>GForest is ready for the next request</h3>";
}

//put the filters into the format that the SOLE scripts require
function formatFilters(){
  var filters=$("#filtersForm").serialize();
  var timber=document.forms['timberLandForm'].elements['timber_button'];
  if(filters.length==0 && timber[0].checked)return('');
 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
 }

 //add on the timberland filter if it is checked
 if(timber[1].checked)timber=true; else timber=false;
 if(timber){
    timber="SITECLCD%201%202%203%204%205%206)RESERVCD%200";
    if(result.length>0)result+=")"+timber; else result=timber;
 }
 
 return(result);
}

//return the users selected data as a zipped csv file
function dataDump(){
  isGForestSubmitOK=true;
 var button=document.reportsForm.radio_button;
 dataType="none";
for(var i=0;i<button.length;i++)
    if(button[i].checked)dataType=button[i].value;

 submitRjob("dataDump");

} 

//submit a url to run one of the SOLE R scripts
//this needs to know what tab called it, so beware if you add new tabs
//@param caller - is this call from an email button
function submitRjob(caller){ 
 
  //if(caller!="sim" && caller!="simEmail")submitTab=getCurrentTab();
  submitTab=getCurrentTab();

  //alert("caller="+caller+"  submitTab="+submitTab);

  if(query.length==0){
    alert("Select some data first? Suggestion: Double Click the map.");
    return;
  }
  if(!isGForestSubmitOK){
      alert("Wait for the previous submission to complete or ClearMap and start over");
      return;
  }

   var vars='yvar='+selectedQuanVar.join('&yvar=') + '&cvar='+selectedQualVar.join('&cvar=');

  if(submitTab==6 && mySecret!=theKey && mySecret!=theKey2 && mySecret!=theTempKey){
     alert("Please login, then re-submit.");
     userLogin();
     return;
   }
  if(submitTab<6 && (vars.indexOf('yvar')==-1 || vars.indexOf('cvar')==-1)){
    alert("Pick a quantitative and a qualitative variable"); return;
  }
  var filters=formatFilters();//get filters in format that SOLE wants
  var Rscript;
  var data="/var/www/html/SOLE/datafiles/"+GRandomDataFileName+".Rdata";
 
  //initialize Rscript at tab 4
   Rscript=document.tablesForm.script;
  if(submitTab==5)Rscript=document.mapsForm.script;
  else if(submitTab==6){
    vars="dumVar=0";//variables form not used, but this is a place holder 
     Rscript=document.reportsForm.script;
     var scriptIndex=Rscript.selectedIndex;
     var tempName="";
     if(scriptIndex!=-1)tempName=Rscript.options[scriptIndex].value;
     if(tempName.indexOf("conversion")>-1 && mySecret!=theKey2){
      alert("Please enter the conversion report password, then resubmit.");
      userLogin();
      return;
     }
  }
  var scriptIndex=Rscript.selectedIndex;
  if(caller!="dataDump" && caller!="sim" && caller!="simEmail" && scriptIndex==-1){
     alert("Select an option from the Analysis, Maps or Reports tab."); return;
  }

  isGForestSubmitOK=false; //if you got here, then it will be submitted
  var pars=vars+'&data='+data;
  if(filters.length>0)pars+='&filter='+filters;
  if(scriptIndex!=-1)Rscript=Rscript.options[scriptIndex].value;

  if(caller=="dataDump"){
    Rscript="table/dataDump.R";
    pars='type='+dataType+'&data='+data+'&filter='+filters;
  }
 
  if(caller=="sim" || caller=="simEmail"){
    Rscript="GReport/sim/report.R";
     pars='data='+data+'&filter='+filters;
     for(var i=0;i<simCenter.length;i++){
     pars+="&Type="+simCenter[i].Type+"&Lat="+simCenter[i].Lat+"&Lon="+simCenter[i].Lon+"&Rad="+simCenter[i].Rad+"&Take="+simCenter[i].Take;
    }
  }

  if((caller=='email' || caller=='simEmail') && isGForestData){
    submitEmailJob(Rscript,pars); return;
  }

  document.getElementById("temp").innerHTML="Submitting job";
   $("#temp").load("html/working0.html");
  if(!isGForestData){
    prepGForestData(caller);
    isGForestData=true;
    return;
  }
  
 
  // alert(Rscript+'?'+pars);
 
  var url = '/cgi-bin/RSOLE/GR.cgi/'+Rscript;
   $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showJob
      }); 

   return;
}

//this is purely to keep the user from making multiple submissions
//while waiting for prepGForestData to complete. It says submitting
//is OK for the millisecond that it takes to call submitRjob, which
//then sets submitting to not OK until the R analysis is complete.
function afterPrepGForestData(){
  isGForestSubmitOK=true; //because submitRjob will be recalled
  submitRjob();
}

//setUp a full data set to correspond to the queries.  This
//allows for filtering and further analysis.  Only do this when
//needed, because its time consuming.
//This is called by submitRjob and it re-calls submitRjob when done.
//Thats probably not good, but it seems to work.  The user won't
//realize that this abomination is happening.
function prepGForestData(caller){
  var url = '/cgi-bin/google/R.cgi/GForestDataPrep.R';
  //alert("submitting to:"+url);
  var pars='data='+GRandomDataFileName;
  var onCompleteFunction=afterPrepGForestData;
  if(caller=='email')onCompleteFunction=submitEmailJob;
  if(caller=='dataDump')onCompleteFunction=dataDump;
  if(caller=='sim')onCompleteFunction=simJob;//see gforestSim.js
  if(caller=='simEmail')onCompleteFunction=simEmailJob;//see gforestSim.js
   $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: onCompleteFunction
      });
}

function submitEmailJob(Rscript,pars){
  if(typeof(Rscript)!='string'){ //go here after prepGForestData
   isGForestSubmitOK=true;
   isGForestData=true;
   submitRjob('email'); //recall submitRjob now that the data are ready
  }
  if(Rscript.indexOf('.R')==-1)return; //XMLrequest junk
    //encode the url that gets passed to the mail program
    //otherwise it will try to decompose it into parameters
    // $$$=? and $$=& and -> is =
  var address=getEmailAddress();
  var url = '/cgi-bin/RSOLE/GncasiMail.pl';
  while(pars.indexOf('&')>0) pars=pars.replace('&','$$$');
  while(pars.indexOf('=')>0) pars=pars.replace('=','->');
  pars='url=/cgi-bin/RSOLE/GR.cgi/'+Rscript+'$$$'+pars;
  pars+='&to='+address+'&subject=Analysis results from GForest';
  // alert("submitEmail url: "+url+" pars: "+pars);
   $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showJob
      });

  document.getElementById("temp").innerHTML="Email submitted";
  isGForestSubmitOK=true;

}

//open a help window to show results of R Rscript analysis
function showJob(msg){
    var win=window.open(); //IE is sensitive to changes in this.
  win.document.write(msg);
  win.document.close();
    win.focus();
   document.getElementById("temp").innerHTML="Job is finished.";
   isGForestSubmitOK=true;
 }

//this gets the email address and makes all email fields match
function getEmailAddress(){
  var t4=document.tablesForm.email.value;
  var t5=document.mapsForm.email.value;
  var t6=document.reportsForm.email.value;
  var t7=document.simForm.email.value;
  var email=t4;

  if(getCurrentTab()==5)email=t5;
  if(getCurrentTab()==6)email=t6;
  if(getCurrentTab()==7)email=t7;
   document.tablesForm.email.value=email;
   document.mapsForm.email.value=email;
   document.reportsForm.email.value=email;
   document.simForm.email.value=email;
  if(!((email.indexOf(".") > 2) && (email.indexOf("@") > 0)))
                    alert("Please enter a valid email address.");
  return(email);
}

//put the server data in JSON format and add it to the my_Markers array
//of objects.  Each element holds all the data sent for 1 plot
function getMarkers(request){
    isGForestSubmitOK=true;
   
    //document.getElementById("temp").innerHTML=request; return;//debug R Rscripts
  var start=0;
  var sep=',EOL,'; //the line separator in the server response
  var vSep='@';    //the variable separater (within a line) from server
   my_Markers=new Array();
  // alert("response length "+request.length);
   var end=request.indexOf(sep,start);
   var head=request.slice(start,end).split(vSep); //header record
   start=end+sep.length;
   nTot=head[0]; //total number of plots that met query criterion
    //pull off the first row of variable names
    var end=request.indexOf(sep,start);
     var name=request.slice(start,end).split(vSep);
      start=end+sep.length;
   
   //make varName lower case
    for(var i=0;i<name.length;i++){name[i]=name[i].toLowerCase();}
    

    var count=0;
    try{
  while(start<request.length){//loop will split large responses
    var end=request.indexOf(sep,start);
    //alert("start end "+start+" "+end);
    if(end==-1)break;
    var data=request.slice(start,end).split(vSep);
     start=end+sep.length;
     //now convert to json
     var json="[{";
     for(var j=0;j<name.length;j++){
       if(data[j]=="NA")data[j]='"None"';
       json+=name[j]+": "+data[j];
       if(j<name.length-1)json+=",";
     }
     json+="}]";
     json=eval(json);
     if(count%100==0)document.getElementById("temp").innerHTML="Number of plots received: "+count+" ... still processing...";
     count++;
     my_Markers.push(json[0]);
  }//end while
    }catch(err){alert("error: "+err+", data= "+data);}

  map.clearOverlays();
 if(count==0){
       alert("There were no plots that met the selection criteria!");
       document.getElementById("temp").innerHTML="Query retrieved no plots.";
       return;
 }else{
   document.getElementById("temp").innerHTML="N of plots meeting query criterion: "+nTot+", N displayed: "+count;
 }

   addMarkerIcon(my_Markers); //what icon should it use
   showMarkers(my_Markers);
   if($("#filtersForm").serialize().length>0 && isGForestData){
        document.getElementById("temp").innerHTML+=", <h3>Filters are active.</h3>";
   }else{
    var Q=query.length-1;
    var lat=Math.round(query[Q].Lat*1000)/1000;
    var lon=Math.round(query[Q].Lon*1000)/1000;
    document.getElementById("temp").innerHTML+="<br> Double clicked at LAT:"+lat+", LON:"+lon; 
   }
}

//this is called after a zoom change to see if markers need to be resized
//its a bit time consuming if a redraw is required
//the global variable, markerChangeZoom determines if a redraw is needed
function zoomRedraw(oldLevel,newLevel){
  if(my_Markers.length==0)return;
  if(oldLevel<markerChangeZoom && newLevel>=markerChangeZoom){
     document.getElementById("temp").innerHTML="Resizing Icons";
    showMarkers(my_Markers);
  }
  else if(oldLevel>=markerChangeZoom && newLevel<markerChangeZoom){
    document.getElementById("temp").innerHTML="Resizing Icons";
      showMarkers(my_Markers);
  }
}

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

//put the map back to its initial state
function resetMap(){
  clearMap();
  map.setMapType(G_NORMAL_MAP);
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
}

//clear all markers out of memory and refresh the map
function clearMap(){
  closeFigures();
  my_Markers=new Array();
  query=new Array();
  map.clearOverlays();
  document.getElementById("temp").innerHTML="GForest: A tool for learning about forest resources in the United States. <br><font style='color:red'> The GForest Map layers were updated in January, 2008 and are based on USGS NLCD data.</font>";
  isGForestSubmitOK=true;
   simCenter=new Array();
   submitTab=0;
}

//close the 3d figure windows
function closeFigures(){
  try{
  if(winNcasi_3d)winNcasi_3d.close();
  if(winNcasi_Grow)winNcasi_Grow.close();
  if(winNcasi_Anim)winNcasi_Anim.close();
  if(winNcasi_Tree)winNcasi_Tree.close();
  }catch(err){};
}

//this does a refresh and redraw of all current markers
//call after adding markers to my_Markers or after passing zoom threshold
function showMarkers(markers){
  map.clearOverlays();
  var zm=map.getZoom();
 
  for(var i=0;i<markers.length;i++) {
    var descA=markers[i].sp1+", "+markers[i].sp2;
    var descB="VOL="+markers[i].totvol+", TPA="+markers[i].tottpa+
      ", BA="+markers[i].totba;
    addMarker(markers[i],descA, descB, zm);
  }
}

//this uses the species code to determine the icon to use
//icons are made by makeIcon() called by init()
function addMarkerIcon(markers){
  
  for(var i=0;i<markers.length;i++) {
   var mInd=1; //the marker index  
   if(markers[i].sp1.search("maple")!=-1)mInd=0;
   else if(markers[i].sp1.search("beech")!=-1)mInd=1;
   else if(markers[i].sp1.search("birch")!=-1)mInd=2;
   else if(markers[i].sp1.search("aspen")!=-1)mInd=3;
   else if(markers[i].sp1.search("cherry")!=-1)mInd=4;
   else if(markers[i].sp1.search("spruce")!=-1)mInd=5;
   else if(markers[i].sp1.search("fir")!=-1)mInd=6;
   else if(markers[i].sp1.search("pine")!=-1)mInd=7;
   else if(markers[i].sp1.search("hemlock")!=-1)mInd=8;
   else if(markers[i].sp1.search("redwood")!=-1)mInd=9;
   else if(markers[i].sp1.search("oak")!=-1)mInd=10;
   else if(markers[i].sp1.search("cypress")!=-1)mInd=11;
   else if(markers[i].sp1.search("ash")!=-1)mInd=12;
   else if(markers[i].sp1.search("hophornbeam")!=-1)mInd=13;
   else if(markers[i].sp1.search("elm")!=-1)mInd=14;
   else if(markers[i].sp1.search("hickory")!=-1)mInd=15;
   else if(markers[i].sp1.search("sycamore")!=-1)mInd=16;
   else if(markers[i].sp1.search("cedar")!=-1)mInd=17;
   else if(markers[i].sp1.search("cottonwood")!=-1)mInd=18;
   else if(markers[i].sp1.search("walnut")!=-1)mInd=19;
   else mInd=20;
   markers[i].icon=mInd; //this determines the icon to use
  }
}

//add the markers to the map overlay list
function addMarker(data, describeA, describeB,zoom) {
  //alert("in add marker");
  var iconIndex=data.icon;
  var ST=data.fips.slice(0,2);
  var tmp="3d";
  var url3d="data/"+ST+"/3d/"+data.plot+".png";
  var plot3d="<a href='javascript:void(0)' onclick='make3dGraph();' >3d</a>";

  var urlAnim="data/"+ST+"/anim/"+data.plot+".gif";
  var plotAnim="<a href='javascript:void(0)' onclick='makeAnimGraph();' >3d+</a>"; 

  var urlGrow="data/"+ST+"/grow/"+data.plot+".gif";
  var plotGrow=", <a href='javascript:void(0)' onclick='makeGrowGraph();' >grow</a>"; 
  if(data.isprev=="0") plotGrow=""; 

  var urlTree="/SOLE/datafiles/"+data.plot+".html";
  var treeData="<a href='javascript:void(0)' onclick='makeTreeList();' >data</a>"; 
  
  
  if(iconIndex>=0 && iconIndex<ncasiIcon.length){
    var nIcon;
    if(zoom>=markerChangeZoom)nIcon=ncasiIcon[iconIndex];
    else nIcon=ncasiIcon2[iconIndex];
    var marker = new GMarker(new GLatLng(data.lat,data.lon),{
      title: describeA, icon: nIcon  });	
  } else var marker = new GMarker(new GLatLng(data.lat, data.lon));

    marker.url3d=url3d;
    GEvent.addListener(marker, 'click',
        function() {
	    ncasi_urlAnim=urlAnim;
	    ncasi_url3d=url3d;
            ncasi_urlTree=urlTree;
            ncasi_urlGrow=urlGrow;
            var the_G_url=describeB +", "+plot3d+", "+plotAnim+", "+treeData+plotGrow;
            
	    marker.openInfoWindowHtml(the_G_url);
                    }
    );

    map.addOverlay(marker);
}

//make a tree list
function makeTreeList(){
var url = '/cgi-bin/google/R.cgi/povrayGforest/makeTreeList.R';
    var pars='PLOT='+ncasi_urlTree;

   $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showTreeData
      });

}
//check if the image exists, make the image and/or call the display function
function make3dGraph(){
var url = '/cgi-bin/google/R.cgi/povrayGforest/makeNew3dPlot.R';
    var pars='URL='+ncasi_url3d+'&TYPE=3d';
    $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: show3dGraph
      });

}

//check if the image exists, make the image and/or call the display function
function makeAnimGraph(){
var url = '/cgi-bin/google/R.cgi/povrayGforest/makeNew3dPlot.R';
    var pars='URL='+ncasi_urlAnim+'&TYPE=anim';
      $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showAnimGraph
      });
   
}

//check if the image exists, make the image and/or call the display function
function makeGrowGraph(){
var url = '/cgi-bin/google/R.cgi/povrayGforest/makeGrowPlot.R';
    var pars='URL='+ncasi_urlGrow;
      $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showGrowGraph
      });
   
}


//opens a new window and shows a tree data
function showTreeData() {
  winNcasi_Tree=window.open(ncasi_urlTree,"TreeData","width=640,height=640,resizable=yes,toolbar=no,location=no,directories=no,status=yrd,menubar=no,scrollbars=yes,left=650,top=30");
  try{ //causes a permission denied error on some windows systems
  winNcasi_Tree.focus();
  }catch(err){}
}

//opens a new window and shows a 2d graph
function showGrowGraph() {
  winNcasi_Grow=window.open(ncasi_urlGrow,"Growth","width=640,height=640,resizable=yes,toolbar=no,location=no,directories=no,status=yrd,menubar=no,scrollbars=no,left=660,top=30");
  try{ //causes a permission denied error on some windows systems
  winNcasi_Grow.focus();
  }catch(err){}
}

//opens a new window and shows a 2d graph
function showAnimGraph() {
  winNcasi_Anim=window.open(ncasi_urlAnim,"Animation","width=300,height=300,resizable=yes,toolbar=no,location=no,directories=no,status=yrd,menubar=no,scrollbars=no,left=890,top=395");
  try{ //causes a permission denied error on some windows systems
  winNcasi_Anim.focus();
  }catch(err){}
}


//opens a new window and shows a 3d graph
function show3dGraph(request) {
  //document.getElementById("temp").innerHTML=request; return;//debug R Rscripts
  winNcasi_3d=window.open(ncasi_url3d,"ncasiGraph","width=640,height=640,resizable=yes,toolbar=no,location=no,directories=no,status=yrd,menubar=no,scrollbars=no,left=640,top=10");
  try{
  winNcasi_3d.focus();
  if(winNcasi_Anim)winNcasi_Anim.focus();
  }catch(err){}
}

//make the icons and store them in global arrays.
var ncasiIcon=new Array(); //marker icons to show on the map
var ncasiIcon2=new Array(); //smaller icons for low zoom
function makeIcons(){
  var images=new Array("yellowHwd","greenHwd","blueHwd","redHwd","purpleHwd",
       "redSpruce","blueSpruce","greenSpruce","yellowSpruce","purpleSpruce",
       "blueOdd","yellowOdd","greenOdd","redOdd","purpleOdd",
		       "blueOak","yellowOak","greenOak","redOak","purpleOak",
                        "blueUnKnown");
   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;     
      
    }

    //smaller icons for low zoom levels
   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(10,10);
       icon.iconSize=new GSize(8,12);
       icon.iconAnchor = new GPoint(4,12);
       icon.infoWindowAnchor = new GPoint(4,6);       
       ncasiIcon2[i]=icon;     
      
    }
}

//open a help window.  This uses the SOLE help files for the
//analysis and map functions.  
//@param name - who called this function
function showHelp(name){
  if((name=="dataDescription" || name=="sim") && mySecret!=theKey && mySecret!=theKey2 && mySecret!=theTempKey){
    alert("Please login");
    return;
  }
  var url="help/"+name+".html";
  var Rscript;
  var width=640;
  if(name=='tutorial'){
   url='tutorial/index.html';
   width=1080;
  }
  if(name=='analysis' || name=='maps' || name=='reports'){
    url='../SOLE/help/';

     Rscript=document.tablesForm.script;
    if(name=='maps') Rscript=document.mapsForm.script;
    if(name=='reports')Rscript=document.reportsForm.script;
    if(Rscript.selectedIndex!=-1){
          Rscript=Rscript.options[Rscript.selectedIndex].value;
          Rscript=Rscript.split('.')[0];   
          url+=Rscript+'.html';
    }else url="help/"+name+".html";
  }
  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>375*1.1*1.1)width=375*1.1*1.1;
  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("GForestFilters").style.height=Math.round(height*.5) +'px';
  document.getElementById("GForestVariables").style.height=Math.round(height*.7) +'px'; 
   document.getElementById("gforestTables").style.height=Math.round(height*.3) +'px';
   document.getElementById("gforestMaps").style.height=Math.round(height*.6) +'px'; 
   document.getElementById("gforestReports").style.height=Math.round(height*.175) +'px'; 
 document.getElementById("dataDownload").style.height=Math.round(height*.35) +'px';
   document.getElementById("gforestSim").style.height=Math.round(height*.8) +'px';
  map.checkResize();
}



function init() {
    if (GBrowserIsCompatible()) {
        map = new google.maps.Map2(document.getElementById("map"));
        adjustSize('0');
        map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
	map.addControl(new PromoControl("/"));
        map.addMapType(G_PHYSICAL_MAP); 
        map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	map.disableDoubleClickZoom();
	GEvent.addListener(map,"dblclick",function(overlay,latlng){
			     getQuery(latlng);
			   });
	GEvent.addListener(map,"zoomend",function(oldLevel,newLevel){
			     zoomRedraw(oldLevel,newLevel);
			   });
	GEvent.addListener(map,"infowindowclose",function(){
			     closeFigures();
			   });
        GEvent.addListener(map,"maptypechanged",function(){
                              changeLayer();
			   });
        makeIcons();//do this now while the user is looking at the map
        ncasiTiles();
        map.setMapType(G_PHYSICAL_MAP);
        resetMap();
    }
    
    GRandomDataFileName=Math.random(); //each user gets a random data file name
}

//get rid of global variables and call GUnload
function ncasiUnload(){
  ncasiIcon=null;
  ncasiIcon2=null;
  clearMap();
  centerLatitude=null;
  centerLongitude=null;
  startZoom=null;
  markerChangeZoom=null;
  GUnload();
}

window.onload = init;
window.onunload = ncasiUnload;


//compute the area in the visible window if user is looking at the
//GForest Change layer
function computeWindowArea(){
  document.getElementById("temp").innerHTML="<h4>Visible Region Area Summary ... computing</h4>"+
document.getElementById("temp").innerHTML;
  var bounds=map.getBounds();
  var NE=bounds.getNorthEast();
  var SW=bounds.getSouthWest();
  var NW=new GLatLng(NE.lat(),SW.lng(),true);
  var SE=new GLatLng(SW.lat(),NE.lng(),true);
  //average width of viewing area in meters
  var mWidth=(NW.distanceFrom(NE) + SW.distanceFrom(SE))/2; 
  //average height of viewing area in meters
  var mHeight=(NW.distanceFrom(SW) + NE.distanceFrom(SE))/2; 
  var zoom=map.getZoom();
  var pix=map.getSize(); //size of view in pixels
  
  var pars='zoom='+zoom+'&NElat='+NE.lat()+'&SWlng='+SW.lng()+'&SWlat='+SW.lat()+'&NElng='+NE.lng()+'&width='+pix.width+'&height='+pix.height+'&mWidth='+mWidth+'&mHeight='+mHeight;

  var url = '/cgi-bin/google/R.cgi/chAreaCompute.R';
  if(isGForestAreaSubmitOK){ //don't submit multiple times
      isGForestAreaSubmitOK=false;
    $.ajax({
        type: "GET",
        url: url,
        data: pars,
        success: showChArea
      });
  }else{
    alert("Wait for the forest stat computations to complete");
    isGForestAreaSubmitOK=true;
  }
}

//display the ch forest area results
function showChArea(result){
     isGForestAreaSubmitOK=true;
  document.getElementById("temp").innerHTML=result; return;

}

//user changed the GForest layer
function changeLayer(){
  var gis=document.control_form1.selectGIS;//points to the GIS drop down
 layerSelected=gis.options[gis.selectedIndex].value;
 if(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("temp");
   console.innerHTML=" ";
 if(layerSelected=="forest")
  console.innerHTML="<img src='help/changeKey.gif' alt='key'>";
if(layerSelected=="change")
  console.innerHTML="<img src='help/LandUseKey.jpg' alt='key'>";
if(layerSelected=="canopy")
  console.innerHTML="<img src='help/LGDcnpy.gif' alt='key'>";
if(layerSelected=="impervious")
  console.innerHTML="<img src='help/LGDimpv.gif' alt='key'>";
if(layerSelected=="nlcd01")
  console.innerHTML="<img src='help/LGDnlcd01.gif' alt='key'>";
if(layerSelected=="ned")
  console.innerHTML="<img src='help/LGDned.jpg' alt='key'>";
if(layerSelected=="plots")
  console.innerHTML="<img src='help/LGDplots.jpg' alt='key'>";
if(layerSelected=="ecoFs")
  console.innerHTML="<br><font size='6'><a href='help/Legend_ecoFS.pdf'>Ecological Section Key</a></font><br> <br>";
}

///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=="forest")
   f="/google/tiles/z"+z+"/g/"+xDir+"/g"+a.x+"_"+a.y+"_"+z+".gif";
  if(layerSelected=="county")
   f="/google/tiles/z"+z+"/cnty/"+xDir+"/cnty"+a.x+"_"+a.y+"_"+z+".gif";
  if(layerSelected=="plots")
   f="/google/tiles/z"+z+"/XYfia/"+xDir+"/XYfia"+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=="canopy")
   f="/google/tiles/z"+z+"/cnpy/"+xDir+"/cnpy"+a.x+"_"+a.y+"_"+z+".gif";
   if(layerSelected=="impervious")
   f="/google/tiles/z"+z+"/impv/"+xDir+"/impv"+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";
   if(layerSelected=="ecoFs")
   f="/google/tiles/z"+z+"/ecoFs/"+xDir+"/ecoFs"+a.x+"_"+a.y+"_"+z+".gif";
   if(z<5 || z>13)f="/google/tiles/blank.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('GForest');
  var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "&copy 2009 NCASI from nlcd");
copyCollection2.addCopyright(copyright);

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

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

  //make the a layer to show x,y,z 
 if(2==1){
   var tilelayers3 = [new GTileLayer(copyCollection2, 4, 19)];
   tilelayers3[0].getTileUrl = xyzGetTileUrl;
   tilelayers3[0].isPng=function(){return false;} 
   //tilelayers3[0].getOpacity = function() {return 0.5;}

    var customMap3 = new GMapType(tilelayers3, new GMercatorProjection(20), "xyz", {errorMessage:"No data available"});
   map.addMapType(customMap3); 
 }

}

function xyzGetTileUrl(a,z) {
  var f="/cgi-bin/google/tile.sh?"+"x="+a.x+"&y="+a.y+"&zoom="+z;
   
	return f;
}


