     google.load('visualization', '1', {packages: ['table', 'motionchart', 'annotatedtimeline']});

  $(document).ready(function(){
    var optionList="http://cimearth.org/index.php/cim-earth/optionList";                          
//    document.getElementById("dataSet").selectedIndex=0;
    ShowPopup(dataSetBlurbs["graphUtilDefault"][1]);
    document.getElementById("dataSet").selectedIndex=0;
    document.getElementById("filename").selectedIndex=0;
    document.getElementById("stdDevSelect").selectedIndex=0;
    document.getElementById("data_type").selectedIndex=0;
    clearFiles();
    $("#dataSet").change(function(){
        $("#stdDevSelect").css("display","none");
        $("#stdDevSelect").css("visibility","hidden");
        document.getElementById("data_type").selectedIndex=0;
        document.getElementById("filename").selectedIndex=0;
        var optionList="http://cimearth.org/index.php/cim-earth/optionList";
        $("#filename").load(
          optionList,
          {'defaultHTML':'<option value="graphUtilDefault">Choose Variable to Display</option>', 'setClass':$("#dataSet").val()}, 
          function(){
            $("#filename option").hover(
             function(){
               ShowPopup(variableBlurbs[$(this).val()][1]);
             },
             function(){
             });      
          }
        );
    });
    $("#dataSet option").hover(
      function(){
        ShowPopup(dataSetBlurbs[$(this).val()][1]);
      },
      function(){
      }
    );
    $("#dataSet").keypress(
      function(){
        ShowPopup(dataSetBlurbs[$(this).val()][1]);           
      }
    );
  
    $("#filename").change(function () {
        document.getElementById("stdDevSelect").selectedIndex=0;
        document.getElementById("data_type").selectedIndex=0;
        var doGlobalShare="";
        var doGross="";
        var doPerCapita="";
        $(this).find("option:selected").each(
          function(){   
            if($(this).hasClass("globalShare"))
              doGlobalShare="true";   
            if($(this).hasClass("gross"))
              doGross="true";
            if($(this).hasClass("perCapita"))
              doPerCapita="true";
          }
        );
        $("#data_type").load(
          "http://cimearth.org/index.php/cim-earth/dataTypeList",
          {"doGlobalShare":doGlobalShare, "doGross":doGross, "doPerCapita":doPerCapita},
          function(){
          }
        );     
    });
    $("#filename").keypress(
      function(){
        ShowPopup(variableBlurbs[$(this).val()][1]);           
      }
    );   
    $("#data_type").change(function(){
      uncertaintyString=$("#data_type").val();
      uncertaintyString="devs_"+uncertaintyString;
      $("#filename").find("option:selected").each(function () {
        if($(this).hasClass(uncertaintyString)){
          document.getElementById("stdDevSelect").style.display='';
          document.getElementById("stdDevSelect").style.visibility="visible";
        }
        else{
          document.getElementById("stdDevSelect").style.display='none';
          document.getElementById("stdDevSelect").style.visibility="hidden";
        }
      });
    });
  });
      function clearFiles(){
        $("#filename").find("option:not(:first)").each(function () {
            $(this).css("display","none");
            $(this).css("visibility","hidden");
        });
      }

      function verifyForm(valueArray, countryList)
      {
        /*if(countryList.length==1){
          if(valueArray.uncertainty.value==0){
            alert("Please s
            return false;
          }
        }*/
        return true;
      }

      function selectRich(form){

        form.USA.checked=true;
        form.JAP.checked=true;
        form.EAA.checked=true;
        form.WEU.checked=true;
      }
      function selectPoor(form){
        form.MEX.checked=true;
        form.CAN.checked=true;
        form.OCN.checked=true;
        form.SEA.checked=true;
        form.IND.checked=true;
        form.SOA.checked=true;
        form.BRA.checked=true;
        form.LAM.checked=true;
        form.REU.checked=true;
        form.MNA.checked=true;
        form.AFR.checked=true;
        form.RUS.checked=true;
      }
      function getCurCol(uncertainties, countryArray, i){//this just returns the column we should be looking at within the dataTable.  obviously there are more columns when uncertainties is true.
        var curRow=countryArray[i];
        if(uncertainties)
            return ((3*curRow)+1);
        else
            return (curRow+1);
      }

      function drawVisualization(meansFile, devsFile, totalMeansFile, totalDevsFile, filename, countryArray, unitsArg){
        var uncertainties=(devsFile!='');
        var drawTotal=(totalMeansFile!='');
        var totalUncertainties=(drawTotal&&uncertainties);
        var meansArray=splitString(meansFile);
        if(uncertainties){
          var devsArray=splitString(devsFile);//turn the devsFile into a matrix.  see formLibrary.js for the function splitString.
          var errorMatrix;
          var numUncertainties=document.getElementById("stdDevSelect").value;
          if(numUncertainties==2)
            devsArray=scaleMatrix(devsArray, 2);//if the user wants bigger uncertaint envelope, scale the matrix representing the devsFile.
         
        }         
        var numRegions=meansArray.length;
        var curCol;
        var graphData=new google.visualization.DataTable();//you Must read the documentation for annotatedTimeLine at the googleVIZ website.
        var numYears=meansArray[0].length;
        var i;
        var j;
        var expanded;
        var singleSet;
        graphData.addColumn('date', 'Year');
        for(i=0; i<numRegions; i++){//if uncertainties is true, we want to draw unceratinty envelopes.  So, we add these columns as the upper and lower ends of the envelope
          if(uncertainties)
            graphData.addColumn('number', 'Low $');
          graphData.addColumn('number', regionArray[i]+"$");
          if(uncertainties)
            graphData.addColumn('number', 'High $');
        }
        if(totalUncertainties)
          graphData.addColumn('number', 'Low $');
        graphData.addColumn('number', 'WORLD TOTAL $');
        if(totalUncertainties)
          graphData.addColumn('number', 'High $');
        graphData.addRows(numYears*1);
        for (i in countryArray){
          curCol=getCurCol(uncertainties, countryArray, i);
          singleSet=copyArray(meansArray[countryArray[i]]);
          //alert(singleSet);
          for (j in singleSet){
            if(i==0)
              graphData.setValue(j*1,0, new Date((2003*1)+(j*1),0,1));//first column must be date column.
            expanded=((""+singleSet[j]).expandExponential())*1;
            if(uncertainties){
              graphData.setValue(j*1,(1*curCol), (1*expanded)-(1*devsArray[countryArray[i]][j]));
              graphData.setValue(j*1,(1*curCol)+1, expanded);
              graphData.setValue(j*1,(1*curCol)+2, (1*expanded)+(1*devsArray[countryArray[i]][j]));
            }
            else
              graphData.setValue(j*1, (1*curCol), expanded);
          }
        }
        //now do the TOTAL column if necessary
        if(drawTotal){
          curCol=numRegions+1;
          totalMeansArray=totalMeansFile.split("\n");
          if(totalUncertainties){
            totalDevsArray=totalDevsFile.split("\n");
            curCol=(3*numRegions)+1;
          }
          for(j in totalMeansArray){
            expanded=((""+totalMeansArray[j]).expandExponential())*1;
            if(totalUncertainties){
              graphData.setValue(j*1,(1*curCol), (1*expanded)-(1*totalDevsArray[j]));
              graphData.setValue(j*1,(1*curCol)+1, expanded);
              graphData.setValue(j*1,(1*curCol)+2, (1*expanded)+(1*totalDevsArray[j]));
            }
            else
              graphData.setValue(j*1, (1*curCol), expanded);
          }
        }//done
        /*
        we need to make up a colorArray when there are uncertainty envelopes.  play with the utility.  we need the envelopes to match in color.
        */
        if(uncertainties){
          var colorArray=new Array();
          for (i=0; i<=countryArray.length; i++){
            colorArray[(3*i)]=getColor((1*i));
            colorArray[(3*i)+1]=getColor(1*i);
            colorArray[(3*i)+2]=getColor(1*i);
          }
        }
        
        var view = new google.visualization.DataView(graphData);//dataview just restricts the attention of the google utility so that it only wants to plot the selected countries.
        var filledColumnsArray=getColumnsForView(countryArray, uncertainties, drawTotal, totalUncertainties, numRegions);
        //alert(filledColumnsArray);
        view.setColumns(filledColumnsArray);//getColumnsForView has returned all of the columns that are relevant to the visualization.
        //alert(unitsArg);
        fixTitle(filename, unitsArg);
        var uncertainGraph = new google.visualization.AnnotatedTimeLine(document.getElementById('graphDiv'));
        uncertainGraph.draw(view, {displayAnnotations: true, legendPosition: 'newRow', colors: colorArray, displayZoomButtons: 'false'});
     // var table = new google.visualization.Table(document.getElementById('graphDiv'));
      //table.draw(graphData, {showRowNumber: true});

      }
      function fixTitle(filename, unitsArg){
        unitSelect=document.getElementById("data_type");
        unitChoice=unitSelect.options[unitSelect.selectedIndex].text;
        if(unitSelect.selectedIndex==0)
            unitChoice+="of ";
        htmlString="<h3>"+unitChoice+ " " + filename;
        $("#filename").find("option:selected").each(function () {
          //alert($(this).attr("class"));
          htmlString += " In Selected Regions";
          htmlString += " ("+units[unitsArg]+")</h3>";
          document.getElementById("titleID").innerHTML=htmlString;
        });
      }



      function handleSelection(file, dropdownText, formVals){//this function is a doozie.  retrieving data in javascript is difficult.  this is why you mgiht want to make this page into a php page.
        var countryList=convertList(formVals,8); //see formLibrary.js for a description of convertList();
        var modString="";
        var dirString="";
        var uncertainties=((document.getElementById("stdDevSelect").selectedIndex!=0)&&(document.getElementById("stdDevSelect").style.display==""));//make sure that the uncertainties box is both visible and selected.
        //alert("hhhhhhhhhhhhhhhhey");
        modString=getModString(document.getElementById('data_type').value);
        dirString=getDirString(document.getElementById('dataSet').value);
        if(document.getElementById('data_type').value==""){//make sure the usere has picked something
          alert("Please decide between global industry share, per capita revenue, or gross revenue");
          return false;
        }
        var meanPath="http://cimearth.org/tools/data/"+dirString+modString+"means_"+file;//find out where to look;
        var unitsArg=meanPath+"";//unitsArg tells the draw function where to look within units.js, the array keeping track of units.
        //alert(unitsArg);
        var errPath="http://cimearth.org/tools/data/"+dirString+modString+"devs_"+file;//find out where to look for the uncertainty data
        totalBox=document.getElementById("worldTotal");
        var plotTotal=((totalBox.checked==true)&&(totalBox.style.display==''));//....
        if(plotTotal){//we only define these things in the event that the user wants to plot worldTotal data.
            totalMeanPath="http://cimearth.org/tools/data/"+dirString+modString+"means_TOTAL-"+file;
            if(uncertainties)
                totalErrPath="http://cimearth.org/tools/data/"+dirString+modString+"devs_TOTAL-"+file;
        }
        else{
            totalMeanPath="";
            totalErrPath="";
        }
        if(!verifyForm(formVals, countryList)){
          alert("make a proper selection");
          return false;
        }
        var filename=document.getElementById("filename").options[document.getElementById('filename').selectedIndex].text;//this is a standard trick for returning the text description of an option within a select box.  
        getFilesAndDraw(meanPath, uncertainties, errPath, totalMeanPath, totalErrPath, plotTotal, unitsArg, countryList, filename);
        return false;
      }

      
      function getFilesAndDraw(meanPath, uncertainties, errPath, totalMeanPath, totalErrPath, plotTotal, unitsArg, countryList, filename){
      /*
READ the documentation at the jquery website on the two get functions below.  Okay.  Here, we get the file located at meanPath since thats the only one we are sure to be using.  then there are four cases: plot uncertainties vs dont plot uncertainties, and plot total vs dont plot total.  two times two equals four choices.  in each case we get different data and deliver it to the draw function.  our approach is: treat the case where the user wants to plot uncertainties, and where the user does not want to plot uncertainties.  each of these cases has two subcases: the user may or may not want to plot world totals.
      */
       
        $.get(meanPath, function(meanPath){
          if(uncertainties){//if we are doing uncertainties, get the file located at errpath.  then deal with the worldTotal issue.
            $.get(errPath, function(errPath){
              if(plotTotal){//case 1: plot totals AND do uncertainties.
                $.get(totalMeanPath, function(totalMeanPath){
                  $.ajax({//i just did this fancier ajax get call because i wanted to implement a failure callback.  you should really read the documentation on these functions.
                    type:"GET", 
                    url:totalErrPath, 
                    dataType:"text",
                    success:function(totalErrPath, responseCode){ 
                       //success callback  
                      drawVisualization(meanPath, errPath, totalMeanPath, totalErrPath, filename, countryList, unitsArg);
                    },
                    error:function(){//case 1.5:  plot totals AND do uncertainties but could not find uncertainty data on the worldTotals.
                      alert("WorldTotal uncertainty data is unavailable.");
                      drawVisualization(meanPath, errPath, totalMeanPath, '', filename, countryList, unitsArg);
                    }
                  });
                }, "text");
              }
              else{//case 2:  uncerainties but not worldTotals
                drawVisualization(meanPath, errPath, '', '', filename, countryList, unitsArg);
              }
            }, "text");
          }
          else{//case: do not do uncertainties
            if(plotTotal){//case 3: no uncertainties but DO worldTotals
              $.get(totalMeanPath, function(totalMeanPath){
                drawVisualization(meanPath, '', totalMeanPath, '', filename, countryList, unitsArg);
              }, "text");
            }
            else{//case 4: no uncertainties and no worldTotals.
              drawVisualization(meanPath, '', '','', filename, countryList, unitsArg);
            }
          }
        }, "text");
      }
      function getModString(dataType){
        switch(dataType){
          case "globalShare":
            modString="globalshare";
            break;
          case "perCapita":
            modString="pc";
            break;
          default:
            modString="";
        }
        return modString;
      }
      function getDirString(dataSet){
        switch(dataSet){
          case "elast_sweep":
            dirString="elast_sweep/";
            break;
          case "share_sweep":
            dirString="share_sweep/";
            break;
          default:
            //alert("uh oh");
            dirString="";
        }
        return dirString;
      }
      function ShowPopup(text)
        {
            hp = document.getElementById("hoverpopup");
            par = document.getElementById("hoverparagraph");
            // Set position of hover-over popup
            par.innerHTML=text;

            // Set popup to visible
            hp.style.visibility = "Visible";
        }

      function HidePopup()
      {
          hp = document.getElementById("hoverpopup");
          hp.style.visibility = "Hidden";
      }     
