$(document).ready(function(){
	var iType;
	var iNum;

	if (hPath.length == 1 && !hPath[0].length) {
		iType = 3;
		iNum = -1;
		track("/event/main");
	}
	else if (hPath.length == 2 && hPath[0] == "image" && isNumeric(hPath[1])) {
		iType = 0;
		iNum = parseInt(hPath[1]);
		document.title += ", image: " + iNum;
	}
	else if (hPath.length == 1 && hPath[0] == "comments") {
		iType = 1;
		document.title += ", comments";
		track("/event/comments");
	}
	else if (hPath.length == 2 && hPath[0] == "browse" && hPath[1] == "random") {
		iType = 2;
		track("/event/browse/random");
	}
	else if (hPath.length == 3 && hPath[0] == "browse" && hPath[1] == "start" && isNumeric(hPath[2])) {
		iType = 3;
		iNum = parseInt(hPath[2]);
		track("/event/browse/start/" + iNum);
	}
	else if (hPath.length == 3 && hPath[0] == "browse" && hPath[1] == "mid" && isNumeric(hPath[2])) {
		iType = 4;
		iNum = parseInt(hPath[2]);
		track("/event/browse/mid/" + iNum);
	}
	else if (hPath.length == 3 && hPath[0] == "browse" && hPath[1] == "end" && isNumeric(hPath[2])) {
		iType = 5;
		iNum = parseInt(hPath[2]);
		track("/event/browse/end/" + iNum);
	}
	else {
		track("/event/wtf");
		alert("w t f ?");
		return;
	}

	$("div#switch a").each(function(){
		$(this).attr("href", $(this).attr("href") + "#/" + hPath.join("/"));
	});

	$("div#mid noscript").remove();
	$("div#switch").appendTo($("div#left"));

	if (iType == 0 || iType == 1) {
		function details (image_id, email, error) {
			var sErr;

			switch (error) {
				case 1:  sErr = "E-mail required."; break;
				case 2:  sErr = "Restricted e-mail."; break;
				case 3:  sErr = "Incorrect e-mail."; break;
				default: sErr = "OK."; break;
			}

			email = prompt((error ? "Error: " + sErr + "\n" + mdash + mdash + mdash
				+ mdash + mdash + mdash + mdash + mdash + mdash + mdash + mdash + mdash
				+ "\n" : "") + "Type in your e-mail address below (you will be sent the details).", email);

			if (email)
				$.post("/ajax/image/details", { id: image_id, email: email }, function (data) {
					inputValue($("div#cmnt > form > input[name='email']"), data.email);

					if (data.error)
						details(image_id, data.email, data.error);
					else {
						track("/event/details/" + image_id);
						alert("Now, check your inbox and/or \"Spam\" folder!\n\nYou should also know"
							+ " that the image was uploaded by \"" + data.up + "\". You can post a comment"
							+ " to the image and s/he\'ll get noticed and probably will be able to tell"
							+ " you sth more.");
					}
				}, "json");
		};

		$("div#gad_3").after("<div id=\"loading\"></div>");

		$.post("/ajax/image", { lead: path[0], id: (iType ? "cmnt" : iNum) }, function (data) {
			track("/event/image/" + data.main);
			var actual = "http://" + hostSt + "/image/big/" + data.hash + ".jpg";
			var pref = "/" + (data.rnd.length ? data.rnd + "/" : "");

			$("div#loading").remove();

			function indecentStr() {
				return (data.adm ? "<a href=\"#\"><span>" + (data.x ? "<i>Indecent.</i> Mark decent." : "<i>Decent.</i> Mark indecent.") + "</span><img src=\"http://" + hostSt + "/layout/ic_" + (data.x ? "denied" : "allowed") + ".png\" /></a>" : "");
			}

			var d_main = "<div class=\"main\"><div class=\"act\">"
				+ "<a href=\"\"><span>Where was the picture found?</span><img src=\"http://" + hostSt + "/layout/ic_question.png\" /></a>"
				+ "<a href=\"" + actual + "\" target=\"_blank\"><span>View in actual size.</span><img src=\"http://" + hostSt + "/layout/ic_actual.png\" /></a>"
				+ "<a href=\"\"><span>Leave your comment!</span><img src=\"http://" + hostSt + "/layout/ic_comment.png\" /></a>"
				+ "<a href=\"" + pref + "#/browse/mid/" + data.main + "\"><span>Back to chronological listing.</span><img src=\"http://" + hostSt + "/layout/ic_back.png\" /></a>"
				+ "<a href=\"http://feeds2.feedburner.com/Cutiess\"><span>Subscribe! &mdash; and stay up to date!</span><img src=\"http://" + hostSt + "/layout/ic_feed.png\" /></a>"
				+ "<a href=\"/upload\"><span>Upload a picture!</span><img src=\"http://" + hostSt + "/layout/ic_upload.png\" /></a>"
				+ indecentStr()
				+ (data.adm ? "<a href=\"\"><span>Delete forever.</span><img src=\"http://" + hostSt + "/layout/ic_delete.png\" /></a>" : "")
				+ "</div><table><tr><td>"
				+ "<a href=\"" + actual + "\" target=\"_blank\">"
				+ "<img src=\"http://" + hostSt + "/image/medium/" + data.hash + ".jpg\" /></a>"
				+ "</td></tr></table></div>";
	
			$("div#gad_3").after(d_main);

			$("div#mid div.main div.act a").hover(function(){ $("span", this).show(); }, function(){ $("span", this).hide(); });
			$("div#mid div.main > table a").hover(function(){ $("div#mid div.main div.act a:eq(1) span").show(); }, function(){ $("div#mid div.main div.act a:eq(1) span").hide(); });
			$("div#mid a[href='" + actual + "']").click(function(){
				track("/event/actual/" + data.main);
			});

			$("div#mid div.main div.act a:eq(0)").click(function(){
				details(data.main, inputValue($("div#cmnt > form > input[name='email']")), 0);
				return false;
			});

			$("div#mid div.main div.act a:eq(2)").click(function(){
				$.scrollTo("div#cmnt > form", 1000);
				return false;
			});

			if (data.adm) {
				$("div#mid div.main div.act a:eq(6)").click(function(){
					var xthis = this;
					$(xthis).hide();
					if (confirm("Are you *REALLY* sure you want to delete the picture?")) {
						$.post("/ajax/image/delete", { id: data.main }, function (newData) {
							if (newData.status) {
								$(xthis).remove();
								window.location = $("div#mid div.main div.act a:eq(3)")[0].href;
							}
							else
								alert("wtf...");
						}, "json");
					}
					else
						$(xthis).show();
					return false;
				});
				function indecentClick(){
					var xthis = this;
					$(xthis).hide();
					$.post("/ajax/image/indecent", { id: data.main, x: (data.x ? 0 : 1)}, function (newData) {
						if (newData.status) {
							data.x = newData.x;
							$(xthis).after(indecentStr());
							$(xthis).remove();
							$("div#mid div.main div.act a:eq(5)").click(indecentClick)
								.hover(function(){ $("span", this).show(); }, function(){ $("span", this).hide(); });
						}
						else
							alert("wtf...");
					}, "json");
					return false;
				}
				$("div#mid div.main div.act a:eq(5)").click(indecentClick);
			}

			function cmntOneJQ (x)
			{
				var cmnt = "";

				cmnt += "<div class=\"c\"><span><a" + (x.url ? " rel=\"nofollow\" target=\"_blank\" href=\"" + x.url + "\" class=\"h\"" : " class=\"nh\"") + ">"
					+ "<img class=\"av\" src=\"http://www.gravatar.com/avatar/" + x.hash + "?d=identicon&amp;s=80&amp;r=x\" alt=\"\" />";

				var c = "";

				if (x.uploader)
					c += "<span class=\"green\"><img src=\"http://" + hostSt + "/layout/ic_upload.png\" alt=\"[uploader]\" /> uploader</span>";
				if (data.adm && data.main == "cmnt")
					c += "<a target=\"_blank\" href=\"" + pref + "#/image/" + x.iid + "\">&laquo;" + x.iid + "&raquo;</a><br />";
				if (!data.adm && x.censored)
					c += "<span class=\"red\"><img src=\"http://" + hostSt + "/layout/ic_denied.png\" alt=\"[censored]\" /> censored</span>";
				else
					c += x.comment;

				if (x.geo.cc)
					cmnt += "<img src=\"http://" + hostSt + "/flags/png/" + x.geo.cc + ".png\" alt=\"[" + x.geo.cc + "]\" /> "
				cmnt += "<strong>" + x.name + "</strong></a><div class=\"i\">"
					+ "<em>" + x.date + "</em>"
					+ (x.url ? "<br />website: <strong>" + x.url + "</strong>" : "")
					+ (x.geo.cc      ? "<br /><img src=\"http://" + hostSt + "/flags/png/" + x.geo.cc + ".png\" alt=\"[" + x.geo.cc + "]\" />" : "")
					+ (x.geo.country ? " "  + x.geo.country : "")
					+ (x.geo.region  ? ", " + x.geo.region  : "")
					+ (x.geo.city    ? ", " + x.geo.city    : "")
					+ "</div></span>"
					+ (data.adm ? " <a href=\"#\"><img src=\"http://" + hostSt + "/layout/ic_" + (x.censored ? "denied" : "allowed") + ".png\" /></a>" : "")
					+ "<div class=\"m\">" + c + "</div>";

				cmnt += "</div>";

				cmnt = $(cmnt);
				$("span:first", cmnt).hover(function(){ $("div.i", $(this)).show(); }, function(){$("div.i", $(this)).hide(); });
				$("span:first + a", cmnt).click(function(){
					var thisdiv = $(this).parent();
					$(this).remove();

					$.post("/ajax/cmnt/censor", { id: x.id, censor: (x.censored ? 0 : 1) }, function (newdata) {
						thisdiv.after(cmntOneJQ(newdata["new"]));
						thisdiv.remove();
					}, "json");

					return false;
				});

				return cmnt;
			};

			function cmntHtml (json)
			{
				var last_comment_id = 0;

				$.each(json.cmnt, function(){
					last_comment_id = this.id;
					$("div#cmnt > form").before(cmntOneJQ(this));
				});

				if (json.cmnt_moar > 0) {
					$("div#cmnt > form").before("<a class=\"load_moar\" href=\"#\">" + json.cmnt_moar + " comment"
						+ (json.cmnt_moar > 1 ? "s" : "")
						+ " more &ndash; load " + (json.cmnt_moar > 1 ? "them" : "it") + "!</a>");

					$("div#cmnt > a.load_moar").click(function(){
						$("div#cmnt > a.load_moar").remove();

						$.post("/ajax/cmnt", { image_id: data.main, comment_id: last_comment_id }, function (newData) {
							cmntHtml(newData);
						}, "json");

						return false;
					});
				}
			};

			$("div#cmnt").html("<form><div class=\"err\"></div>"
				+ "<input type=\"hidden\" name=\"image_id\" value=\"" + data.main + "\" />"
				+ "<input type=\"text\" class=\"x\" name=\"name\" value=\"" + data.form.name + "\" />"
				+ "<input type=\"text\" class=\"x\" name=\"url\" value=\"" + data.form.url + "\" />"
				+ "<input type=\"text\" class=\"x\" name=\"email\" value=\"" + data.form.email + "\" />"
				+ " (sign up at <a href=\"http://gravatar.com/\" rel=\"nofollow\" target=\"_blank\">Gravatar</a> to get your own avatar image)"
				+ "<textarea name=\"comment\"></textarea>"
				+ "<input type=\"submit\" value=\"Save &raquo;\" />"
				+ "</form>");

			inputPrompt($("div#cmnt input.x:eq(0)"), "name");
			inputPrompt($("div#cmnt input.x:eq(1)"), "website (optional)");
			inputPrompt($("div#cmnt input.x:eq(2)"), "e-mail (won't be shown)");
			inputPrompt($("div#cmnt textarea"), "comment");

			formBindSubmit($("div#cmnt > form"), "/ajax/cmnt/save", function(newData){
				$("div#cmnt").prepend(cmntOneJQ(newData["new"]));
				$.scrollTo("div#cmnt > div.c:eq(0)", 1000, {offset: {top: -30, left: 0}});
			}, function(){
				$.scrollTo("div#cmnt > form > div.err", 1000, {offset: {top: -15, left: 0}});
			});

			cmntHtml(data);
		}, "json");
	}
	else {
		$("div#cmnt").remove();

		var d_main = "<div class=\"main\">";
		for (var i = 0; i < 25; i++)
			d_main += "<a class=\"thumb\"></a>";
		d_main += "</div>";

		var d_navi = "<div class=\"navi\">"
			+ "<a class=\"o_rght\">older</a> "
			+ "<a class=\"o_left\">newer</a> "
			+ "Order: <a class=\"o_rand\">random</a> / "
			+ "<a class=\"o_date\">by date</a> "
			+ "</div>";

		d_navi = $(d_navi);
		if (iType == 2) {
			$("a.o_rand", d_navi).addClass("active");
			$("a.o_left", d_navi).remove();
			$("a.o_rght", d_navi).html("draw next");
			$("a.o_rght", d_navi).attr("href", "/#/browse/random");
			$("a.o_date", d_navi).attr("href", "/#/");
		}
		else {
			if (iNum == -1)
				$("a.o_left", d_navi).remove();
			$("a.o_date", d_navi).addClass("active");
			$("a.o_rand", d_navi).attr("href", "/#/browse/random");
		}

		$("div#gad_3").after(d_main);
		$("div#gad_3").after(d_navi);
		$("div#gad_4").before(d_navi.clone(true));

		function useArrmnt (data) {
			var pref = "/" + (data.rnd.length ? data.rnd + "/" : "");

			if (iType == 2) {
				$("div.navi > a.o_rght").attr("href", pref + "#/browse/random");
				$("div.navi > a.o_date").attr("href", pref + "#/");
			}
			else {
				$("div.navi > a.o_rand").attr("href", pref + "#/browse/random");
				$("div.navi > a.o_left").attr("href", pref + "#/browse/end/" + data.im[0][0]);
				$("div.navi > a.o_rght").attr("href", pref + "#/browse/start/" + data.im[data.im.length - 1][0]);
			}

			if (data.rem)
				$("div.navi > a.o_left").remove();

			while ($("div#mid div.main a.thumb").length > data.num)
				$("div#mid div.main a.thumb:last").remove();
			while ($("div#mid div.main a.thumb").length < data.num)
				$("div#mid div.main").append("<a class=\"thumb\"></a>");
			var i = 0;
			$("div#mid div.main a.thumb").each(function(){
				$(this).html(
					$("<img src=\"http://" + hostSt + "/image/small/" + data.im[i][1] + ".jpg\" />")
						.css("visibility", "hidden")
						.load(function(){
							$(this)
								.css("top", ($(this).parent().height() - $(this).height()) / 2)
								.css("visibility", "visible")
						})
				);
				$(this).attr("href", pref + "#/image/" + data.im[i][0]);
				i++;
			});
		}

		$.post("/ajax/page", { type: iType, num: iNum, lead: path[0] }, useArrmnt, "json");
	}

});
