﻿$(function () {
	$("table.stripe tr:even").addClass("stripe");
});

var PopForums = {};

PopForums.areaPath = "/Forums";
PopForums.currentTopicState = null;
PopForums.replyInterval = null;

PopForums.processLogin = function () {
	$.ajax({
		url: PopForums.areaPath + "/Authorization/Login",
		type: "POST",
		data: { email: $("#EmailLogin").val(), password: $("#PasswordLogin").val(), persistCookie: $("#PersistCookie").is(":checked") },
		dataType: "json",
		success: function (result) {
			var loginResult = $("#LoginResult");
			switch (result.Result) {
				case true:
					var destination = $("#Referrer").val();
					location = destination;
					break;
				default:
					loginResult.html(result.Message);
			}
		},
		error: function () {
			var loginResult = $("#LoginResult");
			loginResult.html("There was an unknown error while attempting login");
		}
	});
};

PopForums.topicListSetup = function (forumID) {
	PopForums.topicPreviewSetup();
	var b = $("#NewTopicButton");
	b.click(function () {
		var n = $("#NewTopic");
		n.load(PopForums.areaPath + "/Forum/PostTopic/" + forumID, function () {
			var usePlainText = ($("#IsPlainText").val().toLowerCase() == "true");
			if (!usePlainText) {
				$("#NewTopic #FullText").tinymce({
					script_url: "/scripts/tiny_mce/tiny_mce.js",
					theme: "advanced",
					plugins: "paste,inlinepopups",
					content_css: "/Content/PopForums/Style.css",
					gecko_spellcheck: true,
					mode: "exact",
					init_instance_callback: "PopForums.richEditorComplete"
				});
			}
			n.slideDown();
			b.hide();
		});
	});
};

PopForums.loadReply = function (topicID, postID, replyID) {
	var n = $("#NewReply");
	var path = PopForums.areaPath + "/Forum/PostReply/" + topicID;
	if (postID != null)
		path += "?quotePostID=" + postID;
	if (replyID != null) {
		if (postID == null)
			path += "?replyID=" + replyID;
		else
			path += "&replyID=" + replyID;
	}
	n.load(path, function () {
		var usePlainText = ($("#IsPlainText").val().toLowerCase() == "true");
		if (!usePlainText) {
			$("#NewReply #FullText").tinymce({
				script_url: "/scripts/tiny_mce/tiny_mce.js",
				theme: "advanced",
				plugins: "paste,inlinepopups",
				content_css: "/Content/PopForums/Style.css",
				gecko_spellcheck: true,
				mode: "exact",
				init_instance_callback: "PopForums.richEditorComplete"
			});
		}
		n.slideDown();
		$("#ReplyButton").hide();
		PopForums.scrollToElement("NewReply");
		$("#MorePostsBeforeReplyButton").click(function () {
			$.get(PopForums.areaPath + "/Forum/TopicPartial/" + topicID + "?lastPost=" + PopForums.currentTopicState.lastVisiblePost + "&lowpage=" + PopForums.currentTopicState.lowPage, function (result) {
				var stuff = $(result);
				var links = stuff.filter(".pagerLinks").detach();
				var lastPostID = stuff.filter(".lastPostID").detach();
				PopForums.currentTopicState.lastVisiblePost = lastPostID.val();
				stuff = $("<div>").append(stuff);
				var postStream = $("#PostStream");
				postStream.append(stuff);
				stuff.effect("highlight", 1500);
				links.replaceAll(".pagerLinks");
				$(".postItem img:not('.avatar')").addClass("postImage");
				$(".morePostsButton").remove();
				PopForums.replyInterval = setInterval("PopForums.pollForNewPosts(" + topicID + ")", 1500);
			});
		});
	});
	PopForums.replyInterval = setInterval("PopForums.pollForNewPosts(" + topicID + ")", 1500);
};

PopForums.pollForNewPosts = function (topicID) {
	$.ajax({
		url: PopForums.areaPath + "/Forum/IsLastPostInTopic/" + topicID,
		type: "GET",
		dataType: "text",
		data: "lastPostID=" + PopForums.currentTopicState.lastVisiblePost,
		success: function (result) {
			var lastPostLoaded = result.toLowerCase() == "true";
			if (lastPostLoaded) {
				$("#MorePostsBeforeReplyButton").css("visibility", "hidden");
			} else {
				$("#MorePostsBeforeReplyButton").css("visibility", "visible");
				clearInterval(PopForums.replyInterval);
			}
		},
		error: function () {
		}
	});
};

PopForums.richEditorComplete = function(instance) {
	var isImageEnabled = ($("#IsImageEnabled").val().toLowerCase() == "true");
	if (!isImageEnabled) {
		var imageButton = $(".mce_image");
		imageButton.remove();
	}
};

PopForums.topicSetup = function (topicID, pageIndex, pageCount, replyID) {
	var lastPostID = $("#LastPostID").val();
	PopForums.currentTopicState = new PopForums.TopicState(pageIndex, lastPostID);
	$(".postItem img:not('.avatar')").addClass("postImage");
	$(document).on("click", "#ReplyButton,.replyLink", function () {
		PopForums.loadReply(topicID, null, replyID);
	});
	$(document).on("click", ".quoteLink", function () {
		var postID = $(this).parents(".postItem").attr("postID");
		PopForums.loadReply(topicID, postID, replyID);
	});
	$(document).on("click", ".postNameLink", function () {
		var box = $(this).parents(".postItem").find(".miniProfileBox");
		var userID = $(this).parents(".postItem").attr("userID");
		PopForums.loadMiniProfile(userID, box);
	});
	$(document).on("click", ".voteCount", function () {
		var parent = $(this).parents(".postItem");
		var postID = parent.attr("postID");
		parent.find(".voters").slideDown(function () {
			$(this).load(PopForums.areaPath + "/Forum/Voters/" + postID);
			$(this).mouseleave(function() {
				$(this).hide();
			});
		}).css("display", "block");
	});
	$(document).on("click", ".voteUp", function () {
		var parent = $(this).parents(".postItem");
		var postID = parent.attr("postID");
		var countBox = parent.children(".voteCount");
		$.ajax({
			url: PopForums.areaPath + "/Forum/VotePost/" + postID,
			type: "POST",
			success: function (result) {
				countBox.html(result);
				var voted = parent.find(".voteUp");
				voted.replaceWith('Voted');
			}
		});
	});
	var s = $("#SubscribeButton");
	s.click(function () {
		var asyncResult = $("#AsyncResponse");
		$.ajax({
			url: PopForums.areaPath + "/Subscription/ToggleSubscription/" + topicID,
			type: "POST",
			dataType: "json",
			success: function (result) {
				switch (result.Data.isSubscribed) {
					case true:
						s.val("Unsubscribe");
						break;
					case false:
						s.val("Subscribe");
						break;
					default:
						asyncResult.html(result.Message);
				}
			},
			error: function () {
				asyncResult.html("There was an unknown error while attempting to use subscription");
			}
		});
	});
	var f = $("#FavoriteButton");
	f.click(function () {
		var asyncResult = $("#AsyncResponse");
		$.ajax({
			url: PopForums.areaPath + "/Favorites/ToggleFavorite/" + topicID,
			type: "POST",
			dataType: "json",
			success: function (result) {
				switch (result.Data.isFavorite) {
					case true:
						f.val("Remove From Favorites");
						break;
					case false:
						f.val("Make Favorite");
						break;
					default:
						asyncResult.html(result.Message);
				}
			},
			error: function () {
				asyncResult.html("There was an unknown error while attempting to use favorites");
			}
		});
	});
	$("#TopicModLogButton").click(function () {
		var l = $("#TopicModerationLog");
		if (l.is(":hidden"))
			l.load(PopForums.areaPath + "/Moderator/TopicModerationLog/" + topicID, function () {
				l.slideDown();
			});
		else l.slideUp();
	});
	$(document).on("click", ".postModLogButton", function () {
		var id = $(this).attr("postID");
		var l = $(this).next();
		if (l.is(":hidden"))
			l.load(PopForums.areaPath + "/Moderator/PostModerationLog/" + id, function () {
				l.slideDown();
			});
		else l.slideUp();
	});
	$(document).on("click", ".morePostsButton", function () {
		PopForums.currentTopicState.addEndPage();
		var nextPage = PopForums.currentTopicState.highPage;
		var id = topicID;
		var postStream = $("#PostStream");
		var button = $(this).detach();
		$.get(PopForums.areaPath + "/Forum/TopicPage/" + id + "?page=" + nextPage + "&low=" + PopForums.currentTopicState.lowPage + "&high=" + PopForums.currentTopicState.highPage, function (result) {
			var stuff = $(result);
			var links = stuff.filter(".pagerLinks").detach();
			var lastPostID = stuff.filter(".lastPostID").detach();
			PopForums.currentTopicState.lastVisiblePost = lastPostID.val();
			stuff = $("<div>").append(stuff);
			postStream.append(stuff);
			stuff.effect("highlight", 1500);
			links.replaceAll(".pagerLinks");
			if (PopForums.currentTopicState.highPage != pageCount)
				postStream.append(button);
			$(".postItem img:not('.avatar')").addClass("postImage");
		});
	});
	$(document).on("click", ".previousPostsButton", function () {
		PopForums.currentTopicState.addStartPage();
		var nextPage = PopForums.currentTopicState.lowPage;
		var id = topicID;
		var postStream = $("#PostStream");
		var button = $(this).detach();
		$.get(PopForums.areaPath + "/Forum/TopicPage/" + id + "?page=" + nextPage + "&low=" + PopForums.currentTopicState.lowPage + "&high=" + PopForums.currentTopicState.highPage, function (result) {
			var stuff = $(result);
			var links = stuff.filter(".pagerLinks").detach();
			stuff = $("<div>").prepend(stuff);
			postStream.prepend(stuff);
			stuff.effect("highlight", 1500);
			links.replaceAll(".pagerLinks");
			if (PopForums.currentTopicState.lowPage > 1)
				postStream.prepend(button);
			$(".postItem img:not('.avatar')").addClass("postImage");
		});
	});
};

PopForums.TopicState = function(startPageIndex, lastVisiblePost) {
	this.lowPage = startPageIndex;
	this.highPage = startPageIndex;
	this.lastVisiblePost = lastVisiblePost;
};
PopForums.TopicState.prototype.addEndPage = function() { this.highPage++; };
PopForums.TopicState.prototype.addStartPage = function() { this.lowPage--; };

PopForums.topicPreviewSetup = function() {
	var previewButtons = $(".topicPreviewButton");
	previewButtons.click(function() {
		var id = $(this).attr("topicID");
		var preview = $("#TopicPreview" + id);
		if (preview.is(":hidden")) {
			preview.html("<p>Loading...</p>");
			preview.slideDown();
			$.ajax({
				url: PopForums.areaPath + "/Forum/FirstPostPreview/" + id,
				type: "GET",
				dataType: "json",
				success: function(result) {
					preview.html(result.Data.FullText);
				},
				error: function() {
					preview.html("<p>There was an unknown error getting the preview</p>");
				}
			});
		} else
			preview.slideUp();
	});
	previewButtons.hover(function() {
		$(this).effect("highlight", 3000);
	});
};

PopForums.postNewTopic = function () {
	$.ajax({
		url: PopForums.areaPath + "/Forum/PostTopic",
		type: "POST",
		data: { Title: $("#NewTopic #Title").val(), FullText: $("#NewTopic #FullText").val(), IncludeSignature: $("#NewTopic #IncludeSignature").is(":checked"), ItemID: $("#NewTopic #ItemID").val(), IsPlainText: $("#NewTopic #IsPlainText").val() },
		dataType: "json",
		success: function (result) {
			var r = $("#PostResponseMessage");
			switch (result.Result) {
				case true:
					window.location = result.Redirect;
				default:
					r.html(result.Message);
			}
		},
		error: function () {
			var r = $("#PostResponseMessage");
			r.html("There was an unknown error while trying to post");
		}
	});
};

PopForums.postReply = function () {
	$.ajax({
		url: PopForums.areaPath + "/Forum/PostReply",
		type: "POST",
		data: { Title: $("#NewReply #Title").val(), FullText: $("#NewReply #FullText").val(), IncludeSignature: $("#NewReply #IncludeSignature").is(":checked"), ItemID: $("#NewReply #ItemID").val(), CloseOnReply: $("#CloseOnReply").is(":checked"), IsPlainText: $("#NewReply #IsPlainText").val(), ParentPostID: $("#NewReply #ParentPostID").val() },
		dataType: "json",
		success: function (result) {
			var r = $("#PostResponseMessage");
			switch (result.Result) {
				case true:
					window.location = result.Redirect;
				default:
					r.html(result.Message);
			}
		},
		error: function () {
			var r = $("#PostResponseMessage");
			r.html("There was an unknown error while trying to post");
		}
	});
};

PopForums.loadMiniProfile = function (userID, d) {
	if (d.is(":hidden"))
		d.load(PopForums.areaPath + "/Account/MiniProfile/" + userID, function () {
			d.slideDown();
		});
	else d.slideUp();
};

PopForums.scrollToElement = function(id) {
	var e = document.getElementById(id);
	var t = 0;
	if (e.offsetParent) {
		while (e.offsetParent) {
			t += e.offsetTop;
			e = e.offsetParent;
		}
	} else if (e.y) {
		t += e.y;
	}
	scrollTo(0, t);
};

