//this contains the code to set up reports and send them to a cgi program
//it needs serializedFips created in getFips.js as a global var.

//put global variables first
var coleEzRegressionData;
var unitsConvert=1; //used to convert tonnes/hectare to tons/acre
var unitsValue=0; //number of acres or hectares

//send the cgi request for parameters from COLE database and R
//multiple button presses with IE6 can cause an Ajax freeze
function requestParameters(){
  isParameters=true;
  var suffix=0;
  //alert("count="+Ajax.activeRequestCount);
  if(Ajax.activeRequestCount>0)suffix=1; //on 2nd press, send other file
  else {var myAjax=null; var ajax1=null;}
  var workURL="html/working"+suffix+".html";
  var url = '/cgi-bin/1605b/R.cgi/1605b.R';
  pars=serializedFips;
  var filters=formatFilters();
  if(filters.length>0)pars+='&filter='+filters;
 
  //alert("url: "+url+" pars: "+pars); return;
  if(Ajax.activeRequestCount==0){ //don't submit multiple times
   var myAjax = new Ajax.Request(url,{method: 'get',
                                     parameters: pars,
                                     onComplete: getResults});
 }
  var ajax1=new Ajax.Updater({success: 'report1'},workURL);//show animated gif
}

//class to hold the regression data
function RegressionDataClass(name,a,b,c,d,mean){
  this.name=name;
  this.a=parseFloat(a);
  this.b=parseFloat(b);
  this.c=parseFloat(c);
  this.d=parseFloat(d);
  this.mean=parseFloat(mean);
}
//add prototype class vars
RegressionDataClass.prototype.nObs=-999; //sample size
RegressionDataClass.prototype.aMax=-999; //max age
RegressionDataClass.prototype.aMin=-999; //min age
RegressionDataClass.prototype.aPar=-999; //need live tree parameters for cwd
RegressionDataClass.prototype.bPar=-999;
//add prototype class functions.
RegressionDataClass.prototype.predictCarb= function (age) {
  var y=-999.;

  if(this.name=='treeTPH' || this.name=='standdTPH'){
    y=1-Math.exp(-this.b*age);
    y=this.a*Math.pow(y,3);
    //alert("a="+this.a+"  b="+this.b+" aPar="+this.aPar+" bPar="+this.bPar);
  } else if(this.name=='underTPH'){//understory
    var tree=1-Math.exp(-this.bPar*age);
    tree=this.aPar*Math.pow(tree,3);
    y=tree*Math.exp(this.a-this.b*Math.log(tree+1));
  }else if(this.name=='cwdTPHa'){ 
    var tree=1-Math.exp(-this.bPar*age);
    tree=this.aPar*Math.pow(tree,3);
    y=this.a*tree;
  }else if(this.name=='cwdTPH'){ 
    var tree=1-Math.exp(-this.bPar*age);
    tree=this.aPar*Math.pow(tree,3);
    y=this.a*tree + this.b*Math.exp(-age/this.c);
    if(this.b<0)y=Number("NaN"); //prevent negative values at age 0
  }else if(this.name=='ffCTPHa'){ 
    y=this.a*age/(this.b+age);
  }else if(this.name=='ffCTPH'){ 
    y=this.a*age/(this.b+age);
    y=y+this.c*Math.exp(-(age/this.d))
    if(this.c<0)y=Number("NaN"); //prevent negative values at age 0
  }else if(this.name=='soilC1mTPH'){ 
    y=this.mean;
  }else if(this.name=='soilC1mTPHa'){ 
    y=this.mean*(0.75+0.25*(1.0-Math.exp(-(Math.pow(age/50,2)))));
  }else{y=-999;}


   if(isNaN(y))y=this.mean;
    y=y*unitsConvert*unitsValue;
    y=Math.round(y*1000.)/1000.;
    return y;
}
RegressionDataClass.prototype.toString= function () {
    return this.name+" "+this.a+" "+this.b+" "+this.c+" "+this.d+" "+this.mean+" "+this.aMax;
};
RegressionDataClass.prototype.longName= function () {
  var longName="unknown";
  if(this.name=='treeTPH')longName="Live Tree";
  else if(this.name=='standdTPH')longName="Standing Dead Tree";
  else if(this.name=='soilC1mTPH')longName="Soil (1m)";
  else if(this.name=='underTPH')longName="Understory";
  else if(this.name=='cwdTPH')longName="Down Dead";
  else if(this.name=='ffCTPH')longName="Forest Floor";
  else if(this.name=='cwdTPHa')longName="Down Dead- A";
  else if(this.name=='ffCTPHa')longName="Forest Floor - A";
  else if(this.name=='soilC1mTPHa')longName="Soil (1m) - A";
  return longName;
};


//handle the results from the RScript
function getResults(result){
  //$('report1').innerHTML=result.responseText; return;
  try{
    coleEzRegressionData=new Array(); //global array to hold results
    var sep='<br>'; //the line separator in the server response
    var vSep='@';    //the variable separater (within a line) from server
    var lines=result.responseText.split(sep);
    var head=lines[0].split(vSep); //aMax,aMin,nObs
    for(var i=1;i<lines.length-1;i++){
      var d=lines[i].split(vSep); //"name","a","b","mean"
      var newReg=new RegressionDataClass(d[0],d[1],d[2],d[3],d[4],d[5]);
      newReg.aMax=head[0];
      newReg.aMin=head[1];
      newReg.nObs=head[2];
      newReg.aPar=head[3];
      newReg.bPar=head[4];
      coleEzRegressionData.push(newReg); 
      //alert(i+"  "+coleEzRegressionData[i-1]);
    }

    var aMax=parseFloat(head[0]);
    var aMin=parseFloat(head[1]);
     aMin=mod(aMin,5);
    var age=document.reportForm.Age;
    ageSelections(age,(aMin)*5,aMax,1,0)
    var ageB=document.reportForm.AgeB;
    ageSelections(ageB,(aMin)*5,aMax,1,-1)
    makeCarbonTable();
  }catch(err){alert("getResults: "+err);}
}

//pass a pointer to an age selection list to fill in the range of ages
//aMin=start age, aMax=last age, inc is age increment
function ageSelections(ages,aMin,aMax,inc,add){
  ages.options.length=0; //clear ages
   aMin=5
  for(var i=0;i<1000;i++){
    var a=aMin+i*inc;
    ages.options[i]=new Option(a,a,false, false);
    if(a>aMax)break;
  }
  ages.options[10+add].selected=true;
}

//check if this is an  afforestation or reforestation variables.
//isAForest = T or F to indicate if user wants an afforestation table
//name = the name of the variable to check
//return T or F to indicate if the variable is in this table
function checkTVar(isAForest,name){
       var tVars=new Array("treeTPH","standdTPH","underTPH","cwdTPHa","ffCTPHa","soilC1mTPHa");
       if(!isAForest)  tVars=new Array("treeTPH","standdTPH","underTPH","cwdTPH","ffCTPH","soilC1mTPH");
       var isOK=false;
       for(j=0;j<tVars.length;j++){
	 if(tVars[j]==name){
	   isOK=true;
           break;
	 }
       }
       return(isOK);
}//end function checkTVar


function makeCarbonTable(){
  try{ 
    unitsValue=document.reportForm.acres.value;
    unitsValue=parseFloat(unitsValue)
      if(isNaN(unitsValue)){
       unitsValue=1;
       document.reportForm.acres.value="1";
      }
    var isAForest=document.reportForm.aForestBox[1].checked;
    var isAcres=document.reportForm.acreBox[1].checked;
    var unitsLabel="Tonnes carbon/hectare";
     unitsConvert=1.0;
    if(isAcres){
      unitsLabel=  "English Tons carbon/acre";
      unitsConvert=1/2.2416933; //convert from tonnes/hectare
    }
    var age=document.reportForm.Age;
    var ageB=document.reportForm.AgeB;
    if(age.selectedIndex-ageB.selectedIndex<0){
     ageB.options[age.selectedIndex-1].selected=true;
    }
    age=age.options[age.selectedIndex].value;
     age=parseFloat(age);
     ageB=ageB.options[ageB.selectedIndex].value;
     ageB=parseFloat(ageB);
    
    
    var dat=coleEzRegressionData;
     var  html="<p><b>Calculation Table for Estimating and Reporting Changes in Forest Carbon Stocks for the 1605(b) Greenhouse Gas Registry. States: </b>"
       for(var k=0;k<stLongName.length;k++){
         var sep="";
	 if(stLongName.length>1 && k<(stLongName.length-1))sep=", ";
         if(k==(stLongName.length-1))sep=".";
         html+=stLongName[k]+sep;
       }
     if(countyName.length>0)html+="<b> Counties:</b> ";
        for(var k=0;k<countyName.length;k++){
         var sep="";
	 if(countyName.length>1 && k<(countyName.length-1))sep=", ";
         if(k==(countyName.length-1))sep=".";
         html+=countyName[k]+sep;
       }
	if(filterLabel.length>0)html+="<b> Filters: </b>"+filterLabel;
      html+="<br> <b>Sample Size</b> = "+dat[0].nObs;
     html+=", <b>Units</b> = "+unitsLabel;  
      html+="<table border=1> <tr>";

    //table header row     
       for(var j=0;j<5;j++){
         html+="<th>";
	  if(j==0)
	    html+= "C Pools "; 
	  else if(j==1)
	    html+="C Stock at base age";
          else if(j==2)
	    html+="C Stock in year prior to reporting year";
          else if(j==3)
	    html+="C Stock in reporting year";
          else if(j==4)
            html+="Change in C Stock in Reporting Year";
          html+="</th>";
      }
       html+="</tr>";


       var totb=0,tot1=0,tot2=0;totC=0; //summary statistics;
       
       //main body of table
    for(var i=0;i<dat.length;i++){
       if(!checkTVar(isAForest,dat[i].name))continue;//save this for last row of table
      html+="<tr>";
       if(dat[i].name.indexOf('soilC1mTPH')==-1){
         totb+=dat[i].predictCarb(ageB);//base period
	 tot1+=dat[i].predictCarb(age-1);
         tot2+=dat[i].predictCarb(age);
         totC+=(dat[i].predictCarb(age) - dat[i].predictCarb(age-1));
       }
      for(var j=0;j<5;j++){
        html+="<td>";
	if(j==0)
	   html+=dat[i].longName();
	else if(j==1)
	    html+=dat[i].predictCarb(ageB);//base period
          else if(j==2)
	   html+=dat[i].predictCarb(age-1);
          else if(j==3)
	    html+=dat[i].predictCarb(age);
          else if(j==4){
	    var c=dat[i].predictCarb(age) - dat[i].predictCarb(age-1);
	    c=Math.round(c*1000.)/1000.;
            html+=c;
	  }
         html+="</td>";
      }
      html+="</tr>";
    }

    //non-soil summary row
    var myText="Total nonsoil";
    html+="<tr>";
    for(var j=0;j<5;j++){
       html+="<td>";
       if(j==1)myText=Math.round(totb*1000)/1000.;
       if(j==2)myText=Math.round(tot1*1000)/1000.;
       if(j==3)myText=Math.round(tot2*1000)/1000.;
       if(j==4)myText=Math.round(totC*1000)/1000.;
       html+=myText+"</td>";
    }

    //total carbon row
     var i=5; //index of correct soil parameters
     if(checkTVar(isAForest,"soilC1mTPHa"))i=8;
       var c=0; //hold the soil value to add on
       var myText="Total C";
    html+="</tr> <tr>";
    for(var j=0;j<5;j++){
       html+="<th>";
       if(j==1){
          c=dat[i].predictCarb(ageB);
	  myText=Math.round((totb+c)*1000)/1000.;}
       if(j==2){
	 c=dat[i].predictCarb(age-1);
	 myText=Math.round((tot1+c)*1000)/1000.;}
       if(j==3){
	 c=dat[i].predictCarb(age);
	 myText=Math.round((tot2+c)*1000)/1000.;}
       if(j==4){
	 c=dat[i].predictCarb(age) - dat[i].predictCarb(age-1);
	 myText=Math.round((totC+c)*1000)/1000.;}
       html+=myText+"</th>";
    
    }


  
     html+="</tr> </table>";
   
      var rep=document.getElementById('report1');
      rep.innerHTML=html;

}catch(err){alert("Table: "+err);}
}
