D().define(this, ["parallel", "wait", "next", "call", "loop", "http"]);
// http://ja.wikipedia.org/w/api.php?action=query&list=categorymembers&cmlimit=500&cmtitle=Category:%E4%BA%AC%E9%83%BD%E5%B8%82%E3%81%AE%E7%A5%9E%E7%A4%BE&format=json&callback=foo

function status (msg) {
	document.getElementById("status").innerHTML = msg;
}

var map;

function loadLocal () {
	var icon = new GIcon();
	icon.image            = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
	icon.shadow           = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize         = new GSize(12, 20);
	icon.shadowSize       = new GSize(22, 20);
	icon.iconAnchor       = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	http.get("kyoto.txt").next(function (req) {
		req.responseText.split(/\n/).forEach(function (l) {
			l = l.split(/\s/);
			var obj = {
				title : l[1],
				lat   : l[2],
				lng   : l[3]
			};

			var point  = new GLatLng(obj.lat, obj.lng);
			var marker = new GMarker(point, icon);
			map.addOverlay(marker);

			with ({ obj: obj, marker : marker }) GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml("<a href='http://ja.wikipedia.org/wiki/" + encodeURIComponent(obj.title) + "'>" + obj.title + "</a>");
			});
		});
	});
}

$(function () {
	var category = location.hash ? decodeURIComponent(location.hash.slice(1)):
	                               "Category:京都市の神社";
	document.title = category + " で、緯度経度情報のあるもの一覧";

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(35.024088,135.762324), 13);
	}

	if (!location.hash) loadLocal();

	var initBounds = new GLatLngBounds();

	var icon = new GIcon();
	icon.image            = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	icon.shadow           = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize         = new GSize(12, 20);
	icon.shadowSize       = new GSize(22, 20);
	icon.iconAnchor       = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	var url = "http://ja.wikipedia.org/w/api.php?format=json&action=query&list=categorymembers&cmlimit=500&cmtitle=" + encodeURIComponent(category);
	http.jsonp(url).
	next(function (data) {
		var titles = data.query.categorymembers.map(function (m) { return m.title });
		// console.log(titles);
		return loop({ end : titles.length - 1, step : 10 }, function (n, o) {
			status("Loading: " + n + " / " + titles.length + " (" + (Math.round(n / titles.length * 100)) + "%)");
			var q = [];
			for (var i = 0; i< o.step; i++) {
				q.push(encodeURIComponent(titles[n + i]));
			}
			return http.jsonp("http://ja.wikipedia.org/w/api.php?format=json&action=query&prop=revisions&rvprop=content&titles=" + q.join("|")).
			next(function (res) {
				// console.log(res);
				var latlng = [];
				for (var key in res.query.pages) if (res.query.pages.hasOwnProperty(key)) {
					var page = res.query.pages[key];
					page.revisions[0]["*"].replace(/\{\{ウィキ座標2段度分秒\|(\d+)\|(\d+)\|(\d+)\|N\|(\d+)\|(\d+)\|(\d+)\|E/g, function (_, lat1, lat2, lat3, lng1, lng2, lng3) {
						var obj = {
							title: page.title,
							lat : +lat1 + (+lat2 / 60) + (+lat3 / 60 / 60),
							lng : +lng1 + (+lng2 / 60) + (+lng3 / 60 / 60)
						};
						latlng.push(obj);

						var point  = new GLatLng(obj.lat, obj.lng);
						var marker = new GMarker(point, icon);
						map.addOverlay(marker);

						initBounds.extend(point);

						with ({ obj: obj, marker : marker }) GEvent.addListener(marker, "click", function() {
							marker.openInfoWindowHtml("<a href='http://ja.wikipedia.org/wiki/" + encodeURIComponent(obj.title) + "'>" + obj.title + "</a>");
						});
					});
				}
				
				if (category != "Category:京都市の神社")
				map.setCenter(initBounds.getCenter(), map.getBoundsZoomLevel(initBounds));

//				console.log(latlng);
			});
		});
	}).
	next(function () {
		status("done");
	}).
	error(function (e) {
		alert(e);
	});

});
