$(document).ready(function() {
    $("#postcommentform").submit(onPostCommentFormSubmit);
    $("#postcommentform input, #postcommentform textarea").one('click', function() { if ($(this).val().indexOf("Type your") >= 0 || $(this).val().indexOf("Enter your") >= 0) {
		$(this).val("")
	} });

    countCharacters();
});

function onPostCommentFormSubmit()
{
    var commentForm = $(this);
    var commentBox = $("#comment");

    var hasError = false;

    // extra validation if the user isn't logged in
    if (!commentForm.hasClass("loggedin")) {

        var displayName = $("#displayname");
        var emailAddress = $("#emailaddr");
        var captcha = $("#captcha");

        if (displayName.val() == "") {
            hasError = true;
            displayName.parent().addClass("error");
            displayName.prevAll("label").html("Please provide a display name:");
        }else{
			displayName.parent().removeClass("error");
			displayName.prevAll("label").html("Display Name:");
		}

        if (emailAddress.length) {
			if (emailAddress.val() == "") {
				hasError = true;
				emailAddress.parent().addClass("error");
				emailAddress.prevAll("label").html("Please enter your email address:");
			}
			else 
				if (emailAddress.val().indexOf("@") == -1 || emailAddress.val().indexOf(".") == -1) {
					hasError = true;
					emailAddress.parent().addClass("error");
					emailAddress.prevAll("label").html("Please enter a valid email address:");
				}else{
					emailAddress.parent().removeClass("error");
					emailAddress.prevAll("label").html("Email Address:");
				}
		}

        if(captcha.length){
			if (captcha.val() == "") {
	            hasError = true;
	            captcha.parent().addClass("error");
	            captcha.prevAll("label").html("Please type the two words:");
	        }
		}

    }

    // comment box is required in both instances
    if (commentBox.val() == "") {
        hasError = true;
        commentBox.parent().addClass("error");
        commentBox.prevAll("label").html("Please leave a comment:");
    }else {
		if(commentBox.val() == "Type your comments here."){
	        hasError = true;
	        commentBox.parent().addClass("error");
	        commentBox.prevAll("label").html("Please leave a comment:");
		}else{
	        commentBox.parent().removeClass("error");
	        commentBox.prevAll("label").html("Comment:");
		}
		
	}

    if (!hasError) {
		return true;
        // post form via ajax or simply return true
    }

    return false;
}

function countCharacters()
{
    var max = 3000;
    $('#comment').keyup(function() {
        var textfield = $(this);
        var length = textfield.val().length;
        if(length > max) {
            textfield.val(textfield.val().substr(0, max));
        }

        textfield.prev('.charcount').children('span').html(max - length);
    });
}