var geocoder;

var currline = "";
var curri = 0;
var inputarray;

var my_lat = 0;
var my_lon = 0;

var geo_lat = 0;
var geo_lon = 0;

var map_lat = 0;
var map_lon = 0;

//var start_time = new Date().getTime();

//This sets the number of decimal places for lat and lon
var prec = 100000


// On page load, call this function
function load()
{
    // Create new geocoding object
    geocoder = new GClientGeocoder();

    // reset input and output
    //Must comment out the line below for report website
   // document.theform.input.value = "";
    document.theform.output.value = "";
    
}



function convert_lat(form) {
a=eval(form.a.value)
b=eval(form.b.value)
c=eval(form.c.value)
d=a+((b+c/60)/60)
form.my_lat.value = Math.round(d*prec)/prec
}

function convert_lon(form) {
e=eval(form.e.value)
f=eval(form.f.value)
g=eval(form.g.value)
h=-1*(e+((f+g/60)/60))
form.my_lon.value = Math.round(h*prec)/prec
}



function submitCurrLine()
{
    // grab current line, chop off stuff beyond last comma, and submit
    //currline = inputarray[curri];
    //curri++;
    var lasti = currline.lastIndexOf(",");
    var submitstring = currline.substring(0,lasti);
    geocoder.getLocations(submitstring, writeIt);
}

function wait(msecs)
{
    var start_time = new Date().getTime();
    var cur = start_time;
    while(cur - start_time < msecs)
    {
        cur = new Date().getTime();
    }
} 

function submitCSV()
{
    //var textinput = document.theform.input.value;
    currline = document.theform.input.value;
    //inputarray = textinput.split("\n");
    //curri = 0;
    //submitCurrLine();
}



function writeIt(response)
{
    if(response.Status.code == 200)
    {
        place = response.Placemark[0];
        geo_lat = place.Point.coordinates[1];
        geo_lon = place.Point.coordinates[0];
       
      	document.theform.geo_lat.value = geo_lat;
		document.theform.geo_lon.value = geo_lon;
		document.theform.map_lat.value = geo_lat;
		document.theform.map_lon.value = geo_lon;
    }
   // else
   // {
     //   document.theform.output.value = document.theform.output.value + "\n,," + currline;
   //   alert("Unable to geocode your location.  Please check spelling, zip code, or other information and try again");      
            
  //  }
  
  else
   {
 //   geo_lat = 41.8105778;
 //   geo_lon = -72.2568083;  
    geo_lat = 0;
    geo_lon = 0;  
	document.theform.map_lat.value = geo_lat;
	document.theform.map_lon.value = geo_lon;
   
            
   }

  

   
}

function display_location()
{
document.theform.output.value =  geo_lat + "," + geo_lon + "," + my_lat + "," + my_lon + "," +  currline;
}

function code_address(lat, lon)
{
my_lat = lat;
my_lon = -1*lon;
var loc = my_lat * my_lon
    if(loc > 0)
    {
     submitCSV();
     display_location(); 
    }
    else
    {
       submitCSV();
       submitCurrLine();    
    }
    
}
