$(document).ready(function() {
	$(".up_btn").click(function() {
		var votestotal = $(this).parent().attr("class");
		
		if ($.cookie("logged_in") == "true") {
			if ($(this).attr("src") != "images/up_hover.png") {
				var uid = $.cookie("uid");
				var question_id = $(this).attr("id");
				question_id = question_id.replace("up_", "");
				$(this).attr("src", "images/up_hover.png");
				if ($("#down_" + question_id).attr("src") == "images/down_hover.png") {
					$("#down_" + question_id).attr("src", "images/down.png");
				}
				var votes = $(this).parent().parent().find(".vote_spacer").text();
				var vote_num = new Number(votes);
				if (votestotal == 1) {
					if (vote_num == -1) {
						vote_num = 1;
						$(this).parent().parent().find(".vote_spacer").text(vote_num);
					} else {
						vote_num = vote_num + 1;
						$(this).parent().parent().find(".vote_spacer").text(vote_num);
					}
				} else {
					vote_num = vote_num + 1;
					$(this).parent().parent().find(".vote_spacer").text(vote_num);				
				}
				if (vote_num < 0) {
					$(this).parent().parent().find(".vote_spacer").css("padding-left", "1px");
				} else if (vote_num > 9) {
					$(this).parent().parent().find(".vote_spacer").css("padding-left", "4px");			
				} else {
					$(this).parent().parent().find(".vote_spacer").css("padding-left", "6px");					
				}
				$.post("php/votes.php", {uid: uid, qid: question_id, vote: "up"}, function(data) {});
			}
		} else {
			alert("Sorry, you must be logged in to do this.");
		}
	});
	$(".down_btn").click(function() {
		var votestotal = $(this).parent().attr("class");
		if ($(this).attr("src") != "images/down_hover.png") {
			var uid = $.cookie("uid");
			var question_id = $(this).attr("id");
			question_id = question_id.replace("down_", "");
			$(this).attr("src", "images/down_hover.png");
			if ($("#up_" + question_id).attr("src") == "images/up_hover.png") {
				$("#up_" + question_id).attr("src", "images/up.png");
			}
			var votes = $(this).parent().parent().find(".vote_spacer").text();
			var vote_num = new Number(votes);
			if (votestotal == 1) {
				if (vote_num == 1) {
					vote_num = -1;
					$(this).parent().parent().find(".vote_spacer").text(vote_num);
				}
			} else {
				vote_num = vote_num - 1;
				$(this).parent().parent().find(".vote_spacer").text(vote_num);			
			}
			if (vote_num > 9 || vote_num < 0) {
				$(this).parent().parent().find(".vote_spacer").css("padding-left", "1px");
			} else {
				$(this).parent().parent().find(".vote_spacer").css("padding-left", "6px");			
			}
			$.post("php/votes.php", {uid: uid, qid: question_id, vote: "down"}, function(data) {});
		} else {
			alert("You must be signed in to do this.");
		}
	});
	$(".vote_spacer").each(function (index) {
		var vote_num = new Number($(this).text());
		if (vote_num > 9 || vote_num < 0) {
			$(this).css("padding-left", "1px");
		}	
	});
});
