var voting = false;

$(document).ready(function(){
	$(".upvote").click(function(){ 
		if (!voting) {
			voting = true;
			var id = $(this).attr('id').match(/[0-9]+/);
			if (!$(this).hasClass('upvoted')) {
				$(this).addClass('upvoted');
				$.getJSON('/ajax/upvote/' + id, function(data){ setVote(data); });
			} else {
				$(this).removeClass('upvoted');
				$.getJSON('/ajax/unvote/' + id, function(data){ setVote(data); });
			}
		}
	});
	
	$("#logoutLink").click(function(){
		$(this).unbind('click');
		$(this).html('Logging you out...');
		$.post('/u/logout', $("#logoutform").serialize(), function(resp){
			if (resp.ok)
				document.location.href = document.location.href;
			else
				alert("There was an error logging out! Sorry, you're trapped! Just kidding...");
		}, 'json');
	});
	
	$('#ta').keyup(function() {
		var t = $(this);
		var len = t.val().length;
		if (len >= 420) {
			t.addClass('goneover');
		} else {
			if (t.hasClass('goneover'))
				t.removeClass('goneover');
		}
		$('#charLeft').text(420 - len);
	});

	$(".dnvote").click(function(){ 
		if (!voting) {
			voting = true;
			var id = $(this).attr('id').match(/[0-9]+/);
			
			if (!$(this).hasClass('dnvoted')) {
				$(this).addClass('dnvoted');
				$.getJSON('/ajax/dnvote/' + id, function(data){ setVote(data); });
			} else {
				$(this).removeClass('dnvoted');
				$.getJSON('/ajax/unvote/' + id, function(data){ setVote(data); });
			}
		}
	});
	
	$("#letter_comment").click(function(){
		$(this).css('display', 'none');
		$("#comment_form").slideDown(250);
	});
	
	$("#commentcancel").click(function(){
		$("#comment_form").slideUp(250);
		$("#letter_comment").css('display', 'block');
	});
	
	$(".btncomment").click(function(){
		var cbody = $("#cbody");
		var cmt = cbody.val();
		if (cmt) {
			cbody.val('');
			var pid = $(this).attr('id').match(/(\d+)/);
			$("#comment_form").slideUp(250);
			$("#letter_comment").css('display', 'block');
			$.post('/ajax/comment', { 'post_id' : pid[1], 'cbody' : cmt }, function(resp){
				if (resp) {
					if (resp.error)
						alert(resp.error)
					else {
						var html = '<div class="comment">' + resp.body + '<p>Sincerely, <a href="/by/' + resp.url + '">' + resp.username + '</a></p></div>';
						$("#comments").append(html);
						$("#nocmts").css('display','none');
					}
				} else {
					alert('There was a problem posting your comment. Please try again later.');
				}
			}, 'json');
		} else {
			alert('Please enter a comment!');
		}
	});
	
	$(".deletter").click(function(){
		if (confirm('Are you sure you want to delete this letter? This can\'t be undone!')) {
			var id = $(this).attr('alt');
			$.post('/ajax/unpublish', $("#frmdelete"+id).serialize(), function(response) {
				if (response.redirect)
					document.location.href = response.redirect;
			}, 'json');
		}
	});
});

function setVote(data)
{
  if (data.error)
    return showError(data.error);
    
	if (data.id) {
		var cscore = parseInt($("#sc" + data.id).html().replace(',', '').match(/-?[0-9]+/));
		
		if (data.upvote) {
			$("#up" + data.id).addClass('upvoted');
			$("#dn" + data.id).removeClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		} else if (data.dnvote)	{
			$("#up" + data.id).removeClass('upvoted');
			$("#dn" + data.id).addClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		} else  {
			$("#up" + data.id).removeClass('upvoted');
			$("#dn" + data.id).removeClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		}
		
		voting = false;
	}
}

function showError(msg)
{
  alert(msg + '\nTODO: Replace alerts with something less annoying. (Sorry, still beta)');
  //document.location.href = '/u/register';
}

// addCommas released into public domain by Keith Jenci
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


