var fadeSpeed = 3000;

$(document).ready(function(){
	var authorClicked = false;
	var emailClicked = false;
	var urlClicked = false;
	
	$(".commentAuthor").focus(function(){
		$(this).css('color','#000000');
		if (! authorClicked){
			$(this).attr('value','');
			authorClicked = true;
		}
	});
	
	$(".commentEmail").focus(function(){
		$(this).css('color','#000000');
		if (! emailClicked){
			$(this).attr('value','');
			emailClicked = true;
		}
	});
	
	$(".commentUrl").focus(function(){
		$(this).css('color','#000000');
		if (! urlClicked){
			$(this).attr('value','');
			urlClicked = true;
		}
	});

	ajaxCommentForm();


});

function ajaxCommentForm(){


	//set ajax handler to the comment form
	var options = {target: '#commentsOutput',beforeSubmit:showLoading, success:showResponse};
	function showResponse(){
		$("#ajaxLoading").css('visibility','hidden');
 		$("#commentsOutput").fadeIn("slow");
		$("#commentList").load(commentThread,{},function(){
			$("#commentsOutput").fadeTo(fadeSpeed, 75);
			$("#commentTextField").html('');
			$("#commentTextField").attr('value','');
		});
	}
	
	function showLoading(){
		$("#ajaxLoading").css('visibility','visible');
	}
	
	
	$("#commentSubmit").click(function() {

		$("#realCommentPreview").attr('value','');
		if ($("#commentAuthor").attr('value') == ''){
			showCommentError();
		}else if ($("#commentEmail").attr('value') == ''){
			showCommentError();
		}else if ($("#commentEmail").attr('value')=='Required, will be kept private'){
			showCommentError();
		}else if ($("#commentAuthor").attr('value')=='Required'){
			showCommentError();
		}else {
		
			if ($("#commentUrl").attr('value') == 'Optional'){
			
				$("#commentUrl").attr('value','');
			}
		
			$("#commentsForm").ajaxSubmit(options); 
		}
		return false; 
	});
	
	
	//set ajax handler to the comment form
	var previewOptions = {target: '#commentsOutput',beforeSubmit:showLoading, success:showPreview};
	function showPreview(){
		$("#ajaxLoading").css('visibility','hidden');
 		$("#commentsOutput").fadeIn("slow");
	}
	
	
	
	$("#commentPreview").click(function() {
		$("#realCommentPreview").attr('value','Preview');
		$("#commentsForm").ajaxSubmit(previewOptions); 
    
		return false; 
	});
	
	$("#commentsForm").submit(function(){
		$("#realCommentPreview").attr('value','Preview');
		$(this).ajaxSubmit(previewOptions); 
    
		return false; 
	});
	
	
}

function showCommentError(){
	$("#commentsOutput").html('<h3>Comment Submission Error</h3> <p class="comment-content"><i>Name and email address are required.</i></p>');
	$("#commentsOutput").fadeTo(fadeSpeed, 75);
}
