var geocoder;
var map;
var infoWindow;

function initMap()
{
  
  infoWindow = new google.maps.InfoWindow({
    content: ""
  });
  
	geocoder = new google.maps.Geocoder();

	var latlng = new google.maps.LatLng(38.6, -99); // USA
	var myOptions = {
	  zoom: 4,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}



function initEventListeners()
{
	// FOCUS
	$('.textfield').focus( function()
	{
		
	});
	
	// ENTER
	$('.textfield').keydown(function (e)
	{
		/*if( this.id == "zip" )
		{
			if ( isNaN( e.which ) ) return false;
			this.value = isNaN( parseInt( this.value ) ) ? "" : parseInt( this.value );
		}*/
	
		if (e.which == 13) // ENTER
		{
			if ( this.id == "zip" ) searchZip();
			else searchCityState();
		}
	
	});

}




// INIT
$(document).ready(function()
{
	// MAP
	initMap();
	
	// FOCUS
	initEventListeners();
});



function searchCityState()
{
	geocodeString( $('#cityState').attr('value') );
}
function searchZip()
{
	geocodeString( $('#zip').attr('value') );
}
function go()
{
	if ( $('#cityState').attr('value') != "" ) searchCityState();
	else if ( $('#zip').attr('value') != "" ) searchZip();
}


function geocodeString( addressString )
{
  
  // NOTICE
  $("#notice").text("Searching...");
  $("#notice").show("blind");

	geocoder.geocode( { address: addressString}, function(results, status)
	{
		if (status == google.maps.GeocoderStatus.OK && results.length)
		{
		    // You should always check that a result was returned, as it is
		    // possible to return an empty results object.
		    if (status != google.maps.GeocoderStatus.ZERO_RESULTS)
		    {
				  //map.set_center(results[0].geometry.location);

  				//map.set_zoom(8);
  				/*var marker = new google.maps.Marker(
			  	{
  					position: results[0].geometry.location,
  					map: map
  				});*/
  				
  				// LOAD XML
  				loadAdvisorXml( results[0].geometry.location.lat(), results[0].geometry.location.lng(), 25 );
		    }
		    else
		    {
		      $("#notice").text("We were unable to find any advisors in that area.")
		    }
		}
		else
		{
	      $("#notice").text("We were unable to find any advisors in that area.")
		}
	});
}

function loadAdvisorXml( lat, long, radiusMiles )
{
	var path = "symetra.aspx";
	//var path = "symetra.aspx.xml";
	
	$.get( path, { mode: "latlong", lat: lat, long: long, radius: radiusMiles }, function(xml)
  {
      
      var bounds = new google.maps.LatLngBounds();
      var distance = 0;
      var count = 0;
      
      var maxAdvisors = Math.min( 15, $("Advisor", xml).length );
      
      
      if ( maxAdvisors == 0 )
      {
        map.set_center( new google.maps.LatLng(lat, long) );
        map.set_zoom(6);
        $("#notice").text("We were unable to find any advisors in that area.")
        return false;
      }
      
      
  		// LOOP thru advisors
  		$("Advisor", xml).each(function(id)
  		{
  		  
  		  if ( count < maxAdvisors )
  		  {
          var advisor = $("Advisor", xml).get(id);
    
          var agencyName = $("AgencyName", advisor ).text();
          var address1 = $("Address1", advisor ).text();
          var address2 = $("Address2", advisor ).text();
          var city = $("City", advisor ).text();
          var state = $("State", advisor ).text();
        
          var zip = $("ZipCode", advisor ).text();
          var phone = $("Phone", advisor ).text();
          if ( phone.length == 10 ) // FORMAT PHONE
          {
            phone = phone.substr(0,3) + "-" + phone.substr(3,3) + "-" + phone.substr(6,4);
          }
          
          var email = $("Email", advisor ).text();
          var id = $("id", advisor ).text();
          var distanceToAdvisor = $("Distance_miles", advisor ).text();

          var lat = $("Lat", advisor ).text();
          var lng = $("Long", advisor ).text();
        
          var html =  "<div class='infoWindow'>" +
                        "<h3>" + agencyName + "</h3>" + 
                        "<div>" + address1 + "</div>" + 
                        "<div>" + address2 + "</div>" +
                        "<div>" + city + ", " + state + " " + zip + "</div>" +
                        "<div>" + phone + "</div>" +
                        "<div><a href='mailto:" + email + "' onclick='advisor_email_click(\"" + email + "\")'>" + email + "</a></div>" +
                      "</div>";
        

        
          var latlng = new google.maps.LatLng(lat, lng);
        
          
        
          // EXTEND bounds for current address
          bounds.extend( latlng );
        
          // CAPTURE MAX DISTANCE
          distance = Math.max( distance, distanceToAdvisor );
        
          // INCREMENT COUNT
          count++;
          
          // CREATE MARKER
          var marker = new google.maps.Marker(
          {
            position: latlng,
            map: map,
            title: agencyName
          });
        
          // CLICK handler
          google.maps.event.addListener(marker, 'click', function()
          {
            infoWindow.content = html;
            infoWindow.open(map,marker);
          });
          
          
        }
        
      });
      
      // SET MAP ZOOM AND CENTER
      map.fitBounds( bounds );
      
      // TRACKING
      advisor_find_usage();

      $("#notice").text(count + " advisors found within " + Math.round(distance) + " miles.");
      
  });
    
}


