function setupGowallaStreetview(latlng) {
	function degreesToRadians(deg) {
		return deg * (Math.PI / 180);
	}
	function radiansToDegrees(rad) {
		return rad / (Math.PI / 180);
	}
	function getBearing(from, to) {
		var fromlat = degreesToRadians(from.lat());
		var fromlng = degreesToRadians(from.lng());
		var tolat = degreesToRadians(to.lat());
		var tolng = degreesToRadians(to.lng());
		return (((Math.atan2(Math.sin(tolng - fromlng) * Math.cos(tolat), Math.cos(fromlat) * Math.sin(tolat) - Math.sin(fromlat) * Math.cos(tolat) * Math.cos(tolng - fromlng))/Math.PI) * 180) + 360) % 360;
	}
	if(!Gowalla.streetviewService) Gowalla.streetviewService = new google.maps.StreetViewService();      
	Gowalla.streetviewService.getPanoramaByLocation(latlng, 100, function(data, status) {
		if(status != "OK") {
			var clickEventListener = google.maps.event.addListener(Gowalla.map, "click", function(event) {
				google.maps.event.removeListener(clickEventListener);
				setupGowallaStreetview(event.latLng);
			});
			alert("Unable to show Google Streetview for this spot. :-(\n\nTip: Try clicking a nearby blue road (if one exists) to see if you can view the spot from there.");
			return;
		}
	
		var yaw = getBearing(data.location.latLng, new google.maps.LatLng(Gowalla.spot.lat, Gowalla.spot.lng));
		
		var el=document.createElement("div"),
			c=document.getElementById('main');

		el.id = 'streetview';
		el.style.height = "250px";
		el.style.width = "100%";
		el.style.marginBottom = "10px";	

		c.insertBefore(el, c.childNodes[0]);

		var sv = new google.maps.StreetViewPanorama(el, {
			position: data.location.latLng,
			pov: {
				zoom: 0,
				heading: yaw,
				pitch: 10
			},
			visible: true
		});
		Gowalla.map.setStreetView(sv);
		Gowalla.map.setOptions({streetViewControl: true});

		google.maps.event.addListener(Gowalla.map, "click", function(event) {
			var yaw = getBearing(event.latLng, new google.maps.LatLng(Gowalla.spot.lat, Gowalla.spot.lng));
			var pov = sv.getPov();
			pov.heading = yaw;
			sv.setPosition(event.latLng);
			sv.setPov(pov);
		});
	});
}

if(!Gowalla || !Gowalla.spot) {
	alert("You can only use this bookmarklet on Gowalla Spot pages, e.g. http://gowalla.com/spots/23328");
} else if(!document.getElementById('streetview')) {
	Gowalla.map = Gowalla.Map.map;
	setupGowallaStreetview(Gowalla.map.getCenter());
}

