$(function() {
	initGeo();
	if (navigator.geolocation)
		$("#nearby").show();
});

$("#nearby").bind({
	showFinding: function() {
		if (! $(this).hasClass("ready"))
			$(this).trigger("defaultShowFinding");
		$(".retryGeo").hide();
	},
	showError: function(event, error) {
		$(this).trigger("defaultShowError", [
			error,
			{1: "You must agree to share your location for nearby stop finder to work."}
		]);
	},
	specificUpdateGeo: function(event, pos) {
		var lastBigUpdatePos = $(this).data("lastBigUpdatePos");
		pos = pos || $(this).data("pos");
		if (! $(this).hasClass("ready"))
			$(this).find(".status span").text("Finding nearby stops...");
		if (typeof lastBigUpdatePos == "undefined") {
			$(this).trigger("updateStops");
		} else {
			var ca = centralAngle(pos.coords.latitude, pos.coords.longitude, lastBigUpdatePos.coords.latitude, lastBigUpdatePos.coords.longitude),
				$that = $(this);
			if (ca > 7.176e-6) {
				clearTimeout($(this).data("updateTimeout"));
				$(this).data("updateTimeout", setTimeout(function() {
					$that.trigger("updateStopDisplay");
				}, 1000));
				setTimeout(function() {
					$that.trigger("updateStops");
				}, Math.max(0, lastBigUpdatePos.timestamp + 10000 - new Date()));
			} else {
				$(this).trigger("updateStopDisplay");
			}
		}
	},
	updateStops: function() {
		var pos = $(this).data("pos");
		$.ajax({
			url: "/nearbyStops/",
			data: {lat: pos.coords.latitude, lon: pos.coords.longitude},
			context: this,
			success: function(stops) {
				clearTimeout($(this).data("updateTimeout"));
				$(this).data("lastBigUpdatePos", pos)
					.data("stops", stops)
					.trigger("updateStopDisplay");
			},
			error: function() {
				if (! $(this).hasClass("ready")) {
					$(this).find(".status span").text("Can't retrieve nearby stops.");
					$(this).find(".loading").hide();
					$(".retryGeo").show();
				}
				if (! $(this).hasClass("watching"))
					setTimeout(crudeGeo, 10000);
			},
			complete: function(request, status) {
				var $that = $(this);
				clearTimeout($(this).data("refreshTimeout"));
				$(this).data("refreshTimeout",
					setTimeout(
						function() {
							$that.trigger("updateStops");
						},
						(_(["success", "notmodified"]).contains(status) && $(this).hasClass("ready")) ? 600000 : 10000
					)
				);
			},
			datatype: "json"
		});
	},
	updateStopDisplay: function() {
		var pos = $(this).data("pos"), stops = $(this).data("stops");
		$(this).find(".loading").hide();
		if (_(stops).isEmpty()) {
			$(this).removeClass("ready").find(".content > ul").remove();
			$(this).find(".status span").text("No nearby stops found.");
		} else {
			$(this).find(".status span").empty();
			$(".retryGeo").hide();
			_(stops).sortBy(function(stop) {
				return centralAngle(pos.coords.latitude, pos.coords.longitude, stop.lat, stop.lon);
			});
			var allStopHtml = "<ul>";
			_(stops).each(function(stop) {
				var stopHtml = "<a href='/stop/?stopId=" + stop.stopId + "'>" + ent(stop.stopTitle) + "</a>";
				if (pos.coords.accuracy < 400) {
					stopHtml += " - " +
						niceDistAndDir(
							pos.coords.latitude,
							pos.coords.longitude,
							stop.lat,
							stop.lon,
							prefs.units,
							pos.coords.accuracy);
				}
				stopHtml += " <ul>";
				_(stop.dirs).each(function(dir) {
					stopHtml += "<li><strong>" + ent(dir.routeTitle) + "</strong> " + ent(dir.dirTitle) + "</li>";
				});
				stopHtml += "</ul>";
				$(this).find("li[data-stop=" + stop.stopId + "]").html(stopHtml);
				allStopHtml += "<li data-stop='" + stop.stopId + "'>" + stopHtml + "</li>";
			});
			allStopHtml += "</ul>";
			if ($(this).hasClass("ready")) {
				var $that = $(this);
				$(this).find("a").addClass("disabled");
				$(this).find(".content > ul").quicksand(
					$(allStopHtml).children("li"),
					{attribute: "data-stop"},
					function() {
						$that.find("a").removeClass("disabled");
					}
				);
			} else {
				$(this).addClass("ready").find(".content").append(allStopHtml);
			}
		}
	}
});

