//this contains the js code to select states and counties and
//create a serializedFips string to send to a cgi program
//this is saved as a global variable
//&05000&23004 means all counties in state 05 and county 004 in state 23
//the states with all counties selected come first in the string

//put global vars at top
var isState=false;      //indicates if a state is selected
var stName=new Array(); //selected state names
var stLongName=new Array(); //full name of selected states
var stNum=new Array();  //selected state fips numbers
var countyName=new Array();//selected county names
var nStates=0;         //total n of selected states;
var isAllCounties=new Array();//true for states where all counties are selected
var serializedStates=""; //states where all counties are selected (cgi ready)
var serializedFips=""; //selected counties prepped for cgi get
var dir1605b="/1605b/"; //home dir for COLE 1605b project;
var cntyHTML=""; //hold the county selection html code
var stCols=5; //n of columns  in county table , i.e. n of states in a row
var cntAjax=0;   //used to count ajax request completions
var isCnty=true; //are county selections valid
var isFilters=false; //are any filters selected
var filterLabel=""; //a long label for the output table
var isParameters=false; //has database been accessed for carbon parameters
//end global vars


//select all states in a region, by pushing a button under the usa map
function getRegion(){
  var j=0
    for(var i=0; i<arguments.length; i+=3){
	name=arguments[j++];
	code=arguments[j++];
	longName=arguments[j++];
        var wasIn=removeThisState(name);
	if(!wasIn) getState(name,code,longName);
 } 

}
//capture the user state selections from the usmap
//param: name is the state abbreviation
//param: code is the state code
//param: longName is full name of state
function getState(name,code,longName){
   isParameters=false;
   cntyHTML=""; //clear counties html so counties do a reinit
   $("county").innerHTML="";//empty county tab;
   if($("states").innerHTML.indexOf("none")>0){
   stName=new Array();
   stLongName=new Array();
   stNum=new Array();
   isAllCounties=new Array();
   nStates=0;
  } 
  var isUnique=true;
  //check for multiple selection of same state
  for(i=0;i<stName.length;i++) if(stName[i]==name)isUnique=false;
  if(isUnique){
  stName.push(name);
  stLongName.push(longName);
  stNum.push(code);
  isAllCounties.push(true); //initially assume all counties are selected
  }else {removeThisState(name); return;}
  var selects="";
  for(i=0;i<stName.length;i++){
    selects+=stLongName[i]
      if(i<(stName.length-1))selects+=", ";
  }
 $("states").innerHTML="Selected States: <font style='color:red;font-size:125%'>"+selects;
  if(isFilters)checkFilters(1);
  nStates=stName.length;
  if(nStates>0)isState=true;
}


//clear selected states and set selected state message to none
function clearStates(){
  $("states").innerHTML="Selected States: none (Click on a state)";
  isState=false;
  isParameters=false;
  stName=new Array();
  stLongName=new Array();
  stNum=new Array(); 
  isAllCounties=new Array();
  serializedFips="";
  nStates=0;
}

//remove a specific state, used to remove a region
//return true if state was removed, false if state wasn't there
function removeThisState(name){
 if(nStates==0)return;
 var ind=-1;
 for(var i=0;i<stName.length;i++)
   if(stName[i]==name){ind=i; break;}
 if(ind==-1)return(false); //name not found
  if(nStates==1){clearStates(); return(true);}
   nStates--;
  stName.splice(ind,1);
  stLongName.splice(ind,1);
  stNum.splice(ind,1);
  isAllCounties.splice(ind,1); 
 var selects="";
  for(i=0;i<stName.length;i++){
    selects+=stLongName[i]
      if(i<(stName.length-1))selects+=", ";
  }
 $("states").innerHTML="Selected States: <font style='color:red;font-size:125%'>"+selects;
  isParameters=false;
   cntyHTML=""; //clear counties html so counties do a reinit
   return(true)
}

//set up the county tab. This makes an ajax request for each states
//county file.  Only gets states the user requested
//@param tabNum the tab number of the county tab
function initCounty(tabNum){
  if(!isState){
    alert("Please select one or more states.");
    return;
  }
  isCnty=false; //user is in county tab, so you need to check counties later
  toggleTab(tabNum,nTabs,0,0);
  if(cntyHTML!="")return; //user hasn't reselected states since last visit
    //on a slow connection, the user might think nothing is happening
  $("county").innerHTML="Please wait for county selection form to appear";
  cntyHTML="<tr>"; //prepare for the first row of states
  cntAjax=0;
  var i=0;
  for( i=0;i<nStates;i++){
    URL=dir1605b+"html/counties/"+stNum[i]+".html";
    var myAjax=new Ajax.Request(URL,{method: 'get',onComplete: countyHTML});
  }
}
//mod function usage: mod 2 of 16 is  mod(16,2);
function mod(divisee,base) {
	return Math.round(divisee - (Math.floor(divisee/base)*base));
}
//add counties as they become available
function countyHTML(request){
    cntyHTML+="<td>"+request.responseText+"</td>";
    cntAjax++;
    if(mod(cntAjax,stCols)==0) cntyHTML+="</tr> <tr>"; //finish and start a row
    if(cntAjax==nStates){ //this is the last state
      if(mod(cntAjax,stCols)!=0) cntyHTML+="</tr>" //finish last row
	cntyHTML="<table border=1>"+cntyHTML+"</table>" //enclose table
        $("county").innerHTML=cntyHTML; //put table into web page
      cntAjax=0;
    }
}


//go here when user clicks filters tab
function initFilters(tabNum){
  if(!isState){
    alert("Please select one or more states.");
    return;
  }
  toggleTab(tabNum,nTabs,0,0);
  isFilters=true;
}



//check if filter selections are sensible for the selected states
//filterData[i][0] is ith state code, [i][j] is state i forest type code
//@param tabNum - the tab that made the call
function checkFilters(tabNum){
  isParameters=false;
  var isAllFiltersOK=true; //remains true if no invalid filters are selected
  var els= Form.getElements('filtersForm'); 
  for(var i=0;i<els.length;i++){
    var wasBadSelection=false;
    if(els[i].type=="select-multiple"){
      var pick=els[i].options[0].value.split(')');
      var filterData=null;
      var isFVar=false;
      for(var j=0;j<filterCheck.length;j++){
	if(filterCheck[j].fVar==pick[0]){
	  filterData=filterCheck[j].data;
          isFVar=true;
          break;
	}
      }
      if(isFVar){ //alert(stNum[0]+" "+pick[1]);
	for(var k=0;k<els[i].options.length;k++){ //check all selected options
         if(!els[i].options[k].selected) continue;
          var isPickOK=false;
          var pVal=els[i].options[k].value.split(')');
	  for(var s=0;s<stNum.length;s++){ //check all selected states
	    for(var f=0;f<filterData.length;f++){ //ok options by state
	      if(filterData[f][0]!=parseFloat(stNum[s]))continue;
	    for(var p=0;p<filterData[f].length;p++){
	      if(pVal[1]==filterData[f][p]){isPickOK=true; break;}
	    }
	    if(isPickOK)break;
	  }
	  if(isPickOK)break;
	}
           if(!isPickOK){
                   els[i].options[k].selected=false;
                   wasBadSelection=true; 
                   isAllFiltersOK=false;
	   }  
	}
      }
if(wasBadSelection)alert(pick[0]+" values that are not in database for the chosen state(s) cannot be selected.");
    }
  }
  if(!isAllFiltersOK && tabNum==4)tabNum=3; //don't go to report tab yet
  return(tabNum);
}





function clearFilters(){
  ifFilters=false;
 document.getElementById("filtersForm").reset()
}

//put the filters into the format that the COLE scripts require
function formatFilters(){
 var els= Form.getElements('filtersForm');
 var result="";
  filterLabel="";
 for(var i=0;i<els.length;i++){
   //alert(Form.Element.Serializers.select(els[i]));
   var val=$F(els[i]).toString();
   if(els[i].type=="select-multiple" && val.length>0){
     var sp=val.split(',');
      var sp1=sp[0].split(')');//sp1[0] is the filter name
     if(result.length>0)sp1[0]=')'+sp1[0];
     result+=sp1[0]+"%20"+sp1[1];
     if(filterLabel.length>0)filterLabel+=": ";
      filterLabel+="<em>"+els[i].name+"</em>: " +sp1[2]; //label for output table
     for(var j=1;j<sp.length;j++){
        sp1=sp[j].split(')');//sp1[1] is filter code, sp1[2] is longname
        result+="%20"+sp1[1];
	filterLabel+=", "+sp1[2];
     }

   }
 }

 return(result);
}


//report functions follow
//do this when the report tab is clicked
//@param tabNum is the tab that called this and should pop up.
function initReport(tabNum){
   if(!isState){
    alert("Please select one or more states.");
    return;
  }
  serializedFips="";
  if(isFilters)tabNum=checkFilters(tabNum);
  isCnty=checkCnty(); //validate counties if not done already
  if(isCnty)toggleTab(tabNum,nTabs,0,0);
 else return;
 
  //get the states where all counties are selected ready for cgi
  var allStates="";
  var i=0;
  for(i=0;i<nStates;i++){
    //000 indicates all counties for this state on the server side
    if(isAllCounties[i]==true)allStates+="&fips="+stNum[i]+"000"; 
  }
   
  serializedFips=allStates+serializedFips;
  if(serializedFips.substr(0,1)=='&')serializedFips=serializedFips.substr(1);
  //alert("to cgi: "+serializedFips);
  //get the carbon parameters
  if(!isParameters)requestParameters();
}
//validate the county selections and form a serialized list of counties
//this depends on the forms remaining in the same configuration
//dont go here if the user never clicked the county selection tab
//   note: the county html files have 2 radio buttons and a select element
//value="All" and "Spe" for type=radio and name=STCODE
//name="fips" for type=select-multiple and id=stName, value=STCODE
function checkCnty(){
 var cf=Form.getElements("cntyForm");
 countyName=new Array();
 if(cf.length/3<nStates)return(true); //user didn't visit cnty tab yet
 var i=0,j,k;
 var indA; //will be set to the all radio button index
 var indC;  //will be set to the county index
 isCnty=false;
 isParameters=false;
 serializedFips="";
 for(i=0;i<nStates;i++){
   indA=3*(i);
   indC=indA+2;
   if(cf[indA].checked){//all counties are selected for this state;
     isAllCounties[i]=true;
     continue;
   }else { isAllCounties[i]=false; 
     var sc=Form.Element.serialize(cf[indC]);
      if(sc==""){
        alert("Select specific counties for "+cf[indC].id+", or check 'All Counties'");
        return(false);
      }
     serializedFips+="&"+sc;
   }
 }
 sc=serializedFips.split("&",-1); //split out each county
  var sc2,sc3="";
 for(i=0;i<sc.length;i++){
   sc2=sc[i].split("%20")[0];//keep the fips values only
   if(sc2=="")continue;
   countyName.push(sc[i].split("%20")[1]);
   sc3+="&"+sc2; //form a proper serialized list of counties
 }
 
 serializedFips=sc3;
  return(true);   
}

//called by onload()
function init(){ 
  toggleTab(1,nTabs,0,1);
  initColeEzTabs();
}

//get rid of global variables t0 clear the browsers memory
function ncasiUnload(){
  filterFORTYPGRP=null;
  coleEzRegressionData=null;  
  stName=null;
  stNum=null;
  serializedStates=null;
  serializedFips=null;
}

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