var qtipSettings = {
	width: 'auto',
	position: {
		corner: {
			target: 'bottomMiddle',
			tooltip: 'topMiddle'
		}
	},
	style: {
		tip: true,
		textAlign: 'center',
		name: 'cream',
		border: {
			radius: 4
		}
	},
	show: {
		delay: 0,
		when: {
			event: 'click'
		}
	},
	hide: {
		when: 'unfocus',
		delay: 1000
	}
};

$(document).ready(function() {
	
	$('.login-required').qtip($.extend(qtipSettings, {
		content: 'You must be logged in to add or report a comment. <a href="' + commentParams.loginUrl + '">Click here</a> to log in now.'
	}));
	
	$('div.toolbar a.comment').click(function() {
		if (!$(this).hasClass('login-required')) {
			smoothScrollTo($('#comments'))
		}
	});
	
	$('h2.comments a').click(function() { 
		if (!$(this).hasClass('login-required')) {
			smoothScrollTo($('#comment-post-setup'));
		} 
	});
	
	$('#btn-choose-poster-prefs').click(function() {
		if ($('#name-option-real').is(':checked')) {
			setCommentName('real');
		} else if ($('#name-option-nickname').is(':checked')) {
			$('#poster-setup').hide();
			$('#choose-nickname').show();
			$('#nickname').focus();
		}
	});
	
	$('#btn-check-availability').click(checkNickname);
	$('#btn-nickname-cancel').click(onNicknameCancel);
	
	$('button.post-comment').live('click', postComment);
	
	$('a.reply-post').live('click', function() {
		clearReplyBoxes();
		var replyBox = $('#comment-post-setup').find('div.post-comment-box').clone().addClass('reply');
		replyBox.find('button').after(
			$('<button>').addClass('reply-cancel').text('Cancel')
		);
		$(this).closest('div.comment, div.comment-alt').find('div.body-inner:first').append(replyBox);
	});
	
	$('button.reply-cancel').live('click', function() {
		if ($.trim( $(this).closest('div.reply').find('textarea').val() ).length == 0) {
			clearReplyBoxes();
		} else if (confirm('Are you sure you want to cancel your post?')) {
			clearReplyBoxes();
		}
	});
	
	$('a.report-post').live('click', function() {
		if (!$(this).hasClass('login-required')) {
			var conf = confirm('Are you sure you want to report this comment?');
			if (conf) {
				var obj = $(this);
				$.post(window.location.pathname, {
					action: 'flagComment',
					commentId: getNumericId(obj.closest('div[id^="comment-"]').attr('id'))
				}, function(data, textStatus){
					if (data.success) {
						obj.replaceWith($('<span>').addClass('reported').text('Reported'));
					} else {
						alert('Error with reporting article.');
					}
				}, 'json');
			}
		}
	});
	
});

function clearReplyBoxes()
{
	$('#comment-listing').find('div.post-comment-box').remove();
}

function postComment()
{
    var self = $(this);
	var editor = $(this).closest('.body-inner').find('textarea');
	var parentCommentId = $(this).closest('div.comment:not(.reply)').attr('id').replace(/comment-/ig, "");
	if ($.trim($(editor).val()).length > 0) {
	    self.attr('disabled', 'disabled').text('Saving...');
	    editor.attr('disabled', 'disabled');
		$.post(window.location.pathname, {
			action: 'postComment',
			body: $(editor).val(),
			parentCommentId: parentCommentId
		}, function(data, textStatus) {
			if (data.success) {
				$('#comment-listing').html(data.listing);
				editor.val('');
				var newComment = $('#comment-' + data.id);
				newComment.addClass('comment-new');
			}
			self.removeAttr('disabled').text('Post Comment');
			editor.removeAttr('disabled');
		}, 'json');
	} else {
		alert('Please write a comment to post.');
		editor.focus();
	}
}

function setCommentName(type, nickname)
{
	if (nickname == undefined) {
		var nickname = null;
	}
	$.post(window.location.pathname, {
		action: 'setCommentName',
		type: type,
		nickname: nickname
	}, function(data, textStatus) {
		if (data.success) {
			if ($('#manage-content').length > 0) { // On manage account page
				window.location.href = settings.baseUrl + '/member/manage/account/section/comments';
			}
			else { // On article page
				$('#poster-setup, #choose-nickname').remove();
				$('#post-comment').show();
				$('#post-comment div.author').text(data.commentName + ' ');
				if (data.isNickname) {
					$('#post-comment div.author').append($('<img>').attr({
						alt: 'Nickname',
						src: '/images/comments/icon-nick.png'
					}));
				}
			}
		}
	}, 'json');
}

function checkNickname()
{
	$(this).attr('disabled', 'disabled');
	var nickname = $('#nickname').val();
	$.post(window.location.pathname, {
		action: 'checkNickname',
		nickname: nickname
	}, function(data, textStatus) {
		$(this).removeAttr('disabled');
		if (data.success) {
			onNicknameSuccess(nickname);
		} else {
			if (data.error == 'invalid') {
				onNicknameError('The nickname you chose is invalid. Please make sure it is at least 4 characters and only includes only letters and numbers (no spaces or special characters). Please choose another.');
			} else if (data.error == 'taken') {
				onNicknameError('The nickname you chose has already been taken by another member. Please choose another.');
			}
		}
	}, 'json');
}

function onNicknameCancel()
{
	$('#choose-nickname').hide().find('.btn-next').empty().removeClass('message success error no-icon').append(
		$('<button>').attr('type', 'button').text('Check Availability').click(checkNickname)
	).append(
		$('<button>').attr('type', 'button').text('Cancel').click(onNicknameCancel)
	);
	$('#nickname').val('');
	$('#poster-setup').show();
}

function onNicknameSuccess(nickname)
{
	$('#choose-nickname .btn-next').addClass('message success no-icon').html(
		'The nickname you chose is available. Would you like to use it?'
	).append( 
		$('<div>').append( $('<button>').attr('type', 'button').text('Use ' + nickname + ' as my nickname').click(function() {
			setCommentName('nickname', nickname);
		}) ).append(
			$('<button>').attr('type', 'button').text('Cancel').click(onNicknameCancel)
		)
	);
	$('#nickname').focus().select();
}

function onNicknameError(message)
{
	$('#choose-nickname .btn-next').addClass('message error no-icon').html(message).append( 
		$('<div>').append( $('<button>').attr('type', 'button').text('Check Again').click(checkNickname) ).append(
			$('<button>').attr('type', 'button').text('Cancel').click(onNicknameCancel)
		)
	);
	$('#nickname').focus().select();
}
