var geocoder = new google.maps.Geocoder();

function reverseGeoLatLng(latlng, callback, errorfn) {
  var toRet;
  if (geocoder) {
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            callback(results[1].formatted_address);
          }
        } else {
	  errorfn(status);
        }
      });
  }
}


function yql(query, callback) {
     if (!query || !callback) {
        throw new Error('$.YQL(): Parameters may be undefined');
    }

     var encodedQuery = encodeURIComponent(query.toLowerCase());
     url = 'http://query.yahooapis.com/v1/public/yql'
       + '?env=http%3A%2F%2Fdatatables.org%2Falltables.env&q='
       + encodedQuery + '&format=json&callback=?';
    $.getJSON(url, callback);
}

function getLatLongFromIP(ip) {
  yql('select * from ip.location'+
      ' where ip="' + ip + '"', function(data) {
	if (data && data.query.results) {
	  alert(data.query.results.Response.Latitude);
	  alert(data.query.results.Response.Longitude);
	}
      });
}

var defaultLoc = new google.maps.LatLng(37.76, -122.42); // San Fransisco
var defaultLocName = "San Francisco, CA";

var browserSupportFlag =  new Boolean();
var initialLocation = defaultLoc;
var initialLocationName = defaultLocName;
var tryGoogleGears = false;
function getLocation(ip, callback) {
    // Try W3C Geolocation (Preferred)
    if(navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(function(position) {
	    initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	    callback(initialLocation);
	}, function() {
	    tryIPBased();
	});
    } else {
	tryIPBased();
    }
    function tryIPBased() {
	yql('select * from ip.location'+
	    ' where ip="' + ip + '"', function(data) {
		if (data && data.query.results
		    && data.query.results.Response.Latitude != 0
		    && data.query.results.Response.Longitude != 0
		   ) {
		    initialLocation = new google.maps.LatLng(data.query.results.Response.Latitude,
							     data.query.results.Response.Longitude);
		    callback(initialLocation);
		} else {
		    handleNoGeolocation(browserSupportFlag);
		}
	    });
    }
  
    function handleNoGeolocation(errorFlag) {
	initialLocation = defaultLoc;
	callback(initialLocation);
    }
}


/******************** More specific functions *****************/
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var initialMarker;
var fromTouched = false;

function mapInitialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var myOptions = {
      zoom:7,
      disableDoubleClickZoom: true,
      draggable: false,
      scrollwheel: false,
      streeViewControl: false,
      scaleControl: false,
      navigationContol: false,
      keyboardShortcuts: false,
      mapTypeControl: false,
      
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: initialLocation
  }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    initialMarker = new google.maps.Marker({
	position: initialLocation, 
	map: map, 
	title: "From"
    });   


  directionsDisplay.setMap(map);
}
  
var finalDirections;
function calcRoute() {
    initialMarker.setMap(null);
  var start = document.getElementById("buyer_from").value;
  var end = document.getElementById("buyer_to").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
	  finalDirections = response;
	  directionsDisplay.setDirections(response);
      }
    });
}


