$(document).ready(function() {

	var setupSoftware = function() {
		$("#software + ul a").each(function() {
			$(this).prop("title", $(this).text());
		});
	};

	var setupContact = function() {
		$("#contact + ul a").each(function() {
			$(this).prop("title", $(this).text());
		});
	};

	var setupLink = function() {
		$("#link + ul a").each(function() {
			$(this).prop("title", $(this).text());
		});
	};

	var setupUpdate = function() {
		$.ajax({
			async: true,
			cache: false,
			dataType: "json",
			global: false,
			success: function(json) {
				for (var i = 0; i < json.length; ++i) {
					var entry = json[i];
					$("<dt/>", {
						text: entry.date
					}).appendTo($("#update"));
					$("<dd/>", {
						text: entry.value
					}).appendTo($("#update"));
				}
			},
			url: "update.php"
		});
	};

	var format = function(value) {
		value = String(value);
		while (value != (value = value.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
		return value;
	};

	var setup = function() {
		setupSoftware();
		setupContact();
		setupLink();
		setupUpdate();

		$.ajax({
			async: true,
			cache: false,
			data: {referer: document.referrer},
			dataType: "json",
			global: false,
			success: function(json) {
				$("#total").text(json.count);
			},
			url: "counter.php"
		});

		if ($("#download").size() > 0) {
			var $download = $("#download").clone();
			$("#download").remove();
			$download.show();
			$download.removeProp("id");
			$.ajax({
				async: true,
				cache: false,
				data: {page: $("#page").val()},
				dataType: "json",
				global: false,
				success: function(json) {
					for (var i = 0; i < json.length; ++i) {
						var entry = json[i];
						var $node = $download.clone();
						$("table.download tbody").append($node);
						$node.find("td:eq(0)").text(entry.version);
						$node.find("td:eq(1)").text(entry.update);
						$node.find("td:eq(2)").text(format(entry.size));
						var $a = $("<a/>", {
							href: "",
							text: entry.name,
							click: function() {
								$.ajax({
									async: false,
									cache: false,
									data: {name: $(this).text()},
									dataType: "json",
									global: false,
									url: "../download.php",
								});
								location.href = "data/" + $(this).text();
								return false;
							}
						});
						$node.find("td:eq(3)").append($a);
						$node.find("td:eq(4)").text(format(entry.count));
					}
				},
				url: "../download.php"
			});
		}
	}();
});
