// highlight and fade background on named anchors
// requires jquery.color.js http://plugins.jquery.com/project/color
function highlight(elemId) {
	var elem = $(elemId);
	elem.css("backgroundColor", "#ffffff"); // hack for Safari
	elem.animate( {
		backgroundColor : '#e8f0ff'
	}, 0);
	setTimeout(function() {
		$(elemId).animate( {
			backgroundColor : "#ffffff"
		}, 4000);
	}, 1000);
}

function requireSignIn(action, title, prompt) {
	// this should set the field in all three forms
	if( action != null ){
		$("#login-dialog input[name=post]").val(action);
		$("#signInForm input[name=post]").val(action);
	}
	$("#sign-up-prompt").html(prompt);

	// $("#facebookLogin input[name=post]").val(action);
	$("#login-dialog").dialog( {
		autoOpen : true,
		modal : true,
		width : 800,
		minWidth : 200,
		height : 500,
		minHeight : 200,
		closeOnEscape : true,
		title : title
	});

	// $("#recaptcha").html( $("#recaptcha_src").html());
}

function joinIn() {
	var p1 = $("#password").val();
	var p2 = $("#password2").val();
	if (p1 != p2) {
		alert('Passwords did not match! Please try again.');
		$("#password").focus();
		return false;
	} else if ($("#TOS:checked").length == 0) {
		alert("Please agree to the Terms of Service and Privacy Policy before continuing.");
		return false;
	} else {
		return true;
	}
}

function highlightOver() {
	$(this).parent().find("a").addClass("active");
	$(this).parent().find("img.inactive").hide();
	$(this).parent().find("img.active").show();
}

function highlightOut() {
	$(this).parent().find("a").removeClass("active");
	$(this).parent().find("img.active").hide();
	$(this).parent().find("img.inactive").show();
}

function showFollow(node, follow) {
	node.hide();
	if (follow > 0) {
		node.parent().children("#follow").hide();
		node.parent().children("#unfollow").show();
	} else {
		node.parent().children("#unfollow").hide();
		node.parent().children("#follow").show();
	}
}

function showFollowers(node, num) {
	node.parent().find("#num-following-topic").text(num);
}

function follow(node, follow) {

	var diff = node.parent().find("#is-following-topic").val() == "true" ? 1 : 0;

	var other_followers = parseInt(node.parent().find("#num-following-topic").text()) - diff;
	if (isNaN(other_followers)) {
		other_followers = 0;
	}

	// assume that it goes through first
	showFollow(node, follow);
	showFollowers(node, other_followers + follow);

	var subject = node.siblings("#type").val();
	var post_method = "follow/" + subject;

	$
			.ajax( {
				type : "POST",
				url : "post/" + post_method,
				dataType : "text/plain",
				data : {
					id : node.siblings("#id").val(),
					follow : follow,
					ajax : true
				},
				success : function(data) {
					var newfollow = parseInt(data);
					if (isNaN(newfollow)) {
						newfollow = 0;
					}
					showFollow(node, newfollow, 0);
					showFollowers(node, other_followers + newfollow);
					node.parent().find("#is-following-topic").val(newfollow > 0 ? "true" : "false");
				},
				error : function(req, status, error) {
					showFollow(node, follow > 0 ? 0 : 1);
					showFollowers(node, other_followers + (follow > 0 ? 0 : 1));
					node.parent().find("#is-following-topic").val(follow > 0 ? "false" : "true");

					// Using custom response header since Safari doesn't return
					// the statusText correctly
					if (req.status == 403
							&& (req.statusText == "AUTH_REQUIRED" || req.getResponseHeader("FH-Error-Code") == "AUTH_REQUIRED")) {
						if (subject == "question") {
							requireSignIn(post_method, "Thank you for following this question.",
									"We will update you about new answers and comments.");
						} else if (subject == "topic") {
							requireSignIn(post_method, "Thank you for following this topic.",
									"We will inform you weekly about new activity in this topic.");
						} else {
							requireSignIn(post_method, "Thank you for following this " + subject + ".",
									"Sign in to follow this " + subject);
						}
					} else {
						alert("Error: " + req.status + " " + req.statusText);
					}
				}
			});
}

$(document).ready(
		function() {

			$("a.viewAll").click(function() {
				$(this).siblings(".hidden_snippet").show();
				$(this).hide();
				$(this).siblings(".ellipses").hide();
			});

			$("a.whatIs").click(function() {
				var dialogName = '#dialog-' + $(this).attr("id");
				$(dialogName).dialog( {
					autoOpen : true,
					modal : true,
					width : 300,
					minWidth : 300,
					height : 200,
					minHeight : 200,
					closeOnEscape : true
				});
			});

			$('a[href*=#]').click(function() {
				var elemId = '#' + $(this).attr('href').split('#')[1];
				highlight(elemId);
			});

			if (document.location.hash) {
				highlight(document.location.hash);
			}

			$("div.wheel-frame div a").hover(highlightOver, highlightOut);
			$("#topic-bar td.subheader table.subtable td a").hover(highlightOver, highlightOut);

			$('button.unfollow').each(function() {
				var orig_label = $(this).html();
				var new_label = orig_label.replace("Following", "Unfollow");
				$(this).mouseenter(function() {
					$(this).html(new_label);
					$(this).children("div.check").hide();
					$(this).children("div.uncheck").show();
				});
				$(this).mouseleave(function() {
					$(this).html(orig_label);
					$(this).children("div.check").show();
					$(this).children("div.uncheck").hide();
				});
			});

			$('button.follow').click(function() {
				follow($(this), 1);
			});

			$('button.unfollow').click(function() {
				follow($(this), 0);
			});

			$("form.require-sign-in").submit(
					function() {
						if ($("#s_user").length == 0) {
							var data = $(this).serialize() + "&ajax=true";
							var action = $(this).attr("action");
							var post_method = action.replace("post/", "");
							$.ajax( {
								type : "POST",
								url : action,
								data : data,
								success : function(data) {
									location.reload();
								},
								error : function(req, status, error) {
									if (req.status == 403
											&& (req.statusText == "AUTH_REQUIRED" || req
													.getResponseHeader("FH-Error-Code") == "AUTH_REQUIRED")) {
										if (post_method == "question") {
											requireSignIn(post_method, "Thank you for your question.",
													"We will let you know when an answer is posted.");
										} else if (post_method == "answer") {
											requireSignIn(post_method, "Thank you for your answer.",
													"Your answer will be shared with the followers of this question.");
										} else if (post_method == "comment") {
											requireSignIn(post_method, "Thank you for your comment.",
													"Sign up to post your comment.");
										} else if (post_method == "experience") {
											requireSignIn(post_method, "Thank you for sharing your experience.",
													"Sign up to share your experience with the community.");
										} else {
											requireSignIn(post_method, "Sign up to continue.", "Sign up to continue.");
										}
									} else {
										alert("Error: " + req.status + " " + req.statusText);
									}
								}
							}

							);

							return false;
						}
					});

			$("#subscribe-form, #signup-form").submit(function(form){
				form.preventDefault();
				var username=$("input[name=email]", this).val();
				
					$.ajax( {
						type : "POST",
						url :  $(this).attr('action'),
						data : {
							category_id : $("input[name=category_id]", this).val(),
							email : username,
							ajax : true
						},
						success : function(data) {
							if( $("input[name=user_id]", this).length > 0 ){
								window.location.reload();
							} else {
								$("#login-dialog input[name=username]").val(username);
								requireSignIn(null, "Thank you for subscribing.", "Sign up for an account.");
							}
						},
						error : function(req, status, error) {
							if (req.status == 403
									&& (req.statusText == "AUTH_REQUIRED" || req.getResponseHeader("FH-Error-Code") == "AUTH_REQUIRED")) {
								requireSignIn(null, "Thank you for subscribing.", "Sign up for an account.");
							} else {
								alert("Error: " + req.status + " " + req.statusText);
							}
						}
					});
			});
		});


