var start;
var end;
var radius;
var hideRoute;
var map;
var directionsPanel;
var directions;
var geocoder = new GClientGeocoder();
var endCoords;

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function makeTinyUrl() {
	  // set up default options
	  var defaults = {
	    version:    '2.0.1',
	    login:      'markshervey',
	    apiKey:     'R_15b2e0b4ef74eb9de186745b82dc8ea6',
	    history:    '0',
	    longUrl:    escape(document.location + '')
	  };
	
	  // Build the URL to query
	  var daurl = "http://api.bit.ly/shorten?"
	    +"version="+defaults.version
	    +"&longUrl="+defaults.longUrl
	    +"&login="+defaults.login
	    +"&apiKey="+defaults.apiKey
	    +"&history="+defaults.history
	    +"&format=json&callback=?";
		$('shortUrl').append(document.location);
	    // Utilize the bit.ly API
	    $.getJSON(daurl, function(data){
	        // Make a good use of short URL
	        $.each(data.results, function(i, result) {
	        	$('#shortUrl').append("<input id='shareInput' class='textInput' type='text' value='" + result.shortUrl + "'></input><br/>");
	        	$('#shortUrl').append('Share this URL with people instead of the longer URL in the browser address bar.');
	        });
        });
    $('#shareButton').hide();
}

//stole this functionality from here:  http://www.movable-type.co.uk/scripts/latlong.html
function calcRadius(lat1, lon1, lat2, lon2) {
	//var R = 6371; // km  //mean radius of earth in km
	var R = 3956; // miles  //mean radius of earth in miles
	var lat1 = parseFloat(lat1);
	var lon1 = parseFloat(lon1);
	var lat2 = parseFloat(lat2);
	var lon2 = parseFloat(lon2);
	var dLat = (lat2-lat1).toRad();
	var dLng = (lon2-lon1).toRad(); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
			Math.sin(dLng/2) * Math.sin(dLng/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	return d;
}

function addMarker(point, parkMeta) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.image = "images/park.png";
	baseIcon.iconSize = new GSize(15,15);
	baseIcon.shadowSize = new GSize(1,1);
	baseIcon.iconAnchor = new GPoint(0,10);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	var parkIcon = new GIcon(baseIcon);

	
	markerOption = {icon: parkIcon}; 
	var marker = new GMarker(point, markerOption);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(parkMeta[0] + " @ " + parkMeta[1] + "<br/>(" + parkMeta[2] + ")");
		map.setCenter(point);
		map.setZoom(16);
	});
	return marker;
}

function setCenter(lat, lng) {
	var myLatLng;
	myLatLng = new GLatLng(lat, lng);
	map.setCenter(myLatLng);
	map.setZoom(16);
}

		
function initialize() {
	start = $.query.get('start');
	if (start.length == 0) {
		start = "261 Columbus Avenue, San Francisco CA";
	}
	$('#start').val(start);
	end = $.query.get('end');
	if (end.length == 0) {
		end = "Dr Carlton P Goodlett Pl, San Francisco, California 94102";
	}
	$('#end').val(end);
	radius = $.query.get('radius');
	if (radius == "") {
		radius = .1;
	}
	$('#radius').val(radius);
	$('#getRadius').append(radius);
	$('#getEnd').append(end);
	map = new GMap2(document.getElementById("map_canvas"));
	map.setUIToDefault();
	directionsPanel = document.getElementById("route");
	directions = new GDirections(map, directionsPanel);
	GEvent.addListener(directions, "error", handleErrors);
	directions.load("from: " + start + " to: " + end);
	geocoder.getLatLng(end, function(point) {
			if (!point) {
				alert(end + " not found");
			} else {
				var endLat = point.lat() + "";
				var endLng = point.lng() + "";
				lenPoints = points.length;
				var parkingSpaceListLeft = "";
				var parkingSpaceListRight = "";
				j = 0;
				for (var i = 0; i < lenPoints; i++) {
					var parkLat = points[i][1];
					var parkLng = points[i][2];
					distance = calcRadius(parkLat, parkLng, endLat, endLng);
					if (distance < radius) {
						j = j + 1;
						myLatLng = new GLatLng(parkLat, parkLng);
						parkAddress = points[i][0];
						parkCrossStreet = points[i][3];
						parkDescription = points[i][4];
						parkMeta = [parkAddress, parkCrossStreet, parkDescription];
						map.addOverlay(addMarker(myLatLng, parkMeta));
						if (j % 2 == 1) {
							parkingSpaceListLeft = parkingSpaceListLeft + "<li>" + parkMeta[0] + " @ " + parkMeta[1] + "&nbsp;&nbsp;&nbsp;<a onClick='setCenter(" + parkLat + ", " + parkLng + ")' style='text-decoration: underline;'>[zoom]</a><ul><li>" + parkDescription + "</li></ul></li>";
						} else {
							parkingSpaceListRight = parkingSpaceListRight + "<li>" + parkMeta[0] + " @ " + parkMeta[1] + "&nbsp;&nbsp;&nbsp;<a onClick='setCenter(" + parkLat + ", " + parkLng + ")' style='text-decoration: underline;'>[zoom]</a><ul><li>" + parkDescription + "</li></ul></li>";
						}
					}
				}
				$('#spotListLeft').html("<ul>" + parkingSpaceListLeft + "</ul>");
				$('#spotListRight').html("<ul>" + parkingSpaceListRight + "</ul>");
			}
	});
	$('#hideDirectionInput').show();
	$('#showDirectionInput').hide();
	$('#hideSpotList').show();
	$('#showSpotList').hide();
	$('#hideShare').show();
	$('#showShare').hide();
}

function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
   else alert("An unknown error occurred.");
}

// basic show and hide
$(document).ready(function() {
	$('#hideDirectionInput').click( function() {
		$('#directionInput').hide("fast");
		$('#hideDirectionInput').hide();
		$('#showDirectionInput').show();
	});
	$('#showDirectionInput').click( function() {
		$('#directionInput').show("fast");
		$('#hideDirectionInput').show();
		$('#showDirectionInput').hide();
	});
	$('#hideShare').click( function() {
		$('#shareUrl').hide("fast");
		$('#hideShare').hide();
		$('#showShare').show();
	});
	$('#showShare').click( function() {
		$('#shareUrl').show("fast");
		$('#hideShare').show();
		$('#showShare').hide();
	});
	$('#hideSpotList').click( function() {
		$('#spotListContainer').hide("fast");
		$('#hideSpotList').hide();
		$('#showSpotList').show();
	});
	$('#showSpotList').click( function() {
		$('#spotListContainer').show("fast");
		$('#hideSpotList').show();
		$('#showSpotList').hide();
	});
	
	$('a.modal').click(function (e) {
		e.preventDefault();
		$('#modalContent').modal();
	});
});
