$().ready(function(){

    $('textarea[name="comment"]').blur(function(){
		if($(this).val() == ''){$(this).val('Type Your Question Here');}
	});
    
	$('textarea[name="comment"]').focus(function(){
		if($(this).val() == 'Type Your Question Here'){$(this).val('');}
	});

	$('form[id="expert-form"]').submit(function(){
        var result;
        if (validateComment() == true) {
    		$('#askexpert_error').hide();
    		result = do_expert_ajax();
        }
        else {
            result = false;
        }
        return result;
	});
    
    function do_expert_ajax()
    {
        try {
            $.ajax({
                url: $('form[id="expert-form"]').attr('action'),
                type: 'POST',
                dataType: 'html',
                data: $('form[id="expert-form"]').serialize(),
                success: function(data, textStatus){
                    if (data == '') {
                        $('form[id="expert-form"]').hide();
                        $('#askexpert_response').html('Thank you for submitting your question. To see a complete list of previously answered questions, go to the <a href="/ask-mcp/">Ask Gina page</a>.');
                    }
                    else {
                        if (/Error/i.test(data)) {
                            if (/captcha/i.test(data)) {
                                $('#captcha-error').html('Incorrect. Please try again!');
                            }
                            else {
                                $('#askexpert_error').text('There was an error posting your question. Please try again in a few moments.').show();
                            }
                            refreshCaptcha();
                        }
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    $('#askexpert_error').text('There was an error posting your question. Please try again in a few moments.').show();
                }
            });
        }
        catch(err)
        {
            // console.log(err);
        }
        return false;
    }

    /**
    * @desc Validate the comment form (from WP)
    * @return bool
    */
    function validateComment() {
        var result = true;
        var txtComment = $("#comment").val();
        var txtEmail = $("#expert-email").val();
        var txtAuthor = $("#expert-author").val();
        txtAuthor = txtAuthor.replace(/^\s+/g,"").replace(/\s+$/g,"");
        txtEmail = txtEmail.replace(/^\s+/g,"").replace(/\s+$/g,"");
        if (txtAuthor.length == 0) {
            $("#author-error").html("The field 'Name' is required");
            result = false;
        } else {
            $("#author-error").html("");
        }
        if (txtEmail.length == 0) {
            $("#email-error").html("The field 'Email' is required");
            result = false;
        } else {
            $("#email-error").html("");
        }
        //check if this is a valid email
        txtEmail = txtEmail.replace(/^\s+/g,"").replace(/\s+$/g,"");
        if (txtEmail.length != 0) {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (!emailPattern.test(txtEmail)) {
                $("#email-error").html("Please input a valid email");
                result = false;
            } else {
                $("#email-error").html("");
            }
        }
        //validate the comment textarea
        txtComment = txtComment.replace(/^\s+/g,"").replace(/\s+$/g,"");
        if (txtComment.length == 0 || txtComment == 'Type Your Question Here') {
            $("#comment-error").html("Please input some comment");
            result = false;
        } else {
            $("#comment-error").html("");
        }
        return result;
    }
});

function resetCommentForm() {
    $("form#expert-form input[id!='expert-submit'][name!='key'][name!='clear'], form#expert-form textarea").val('');
}

function refreshCaptcha() {
    d = new Date();
    $("#captchaImage").attr('src', $("#captchaImage").attr("src").replace(/\?(.*)/, '\?'+d.getTime()));
    $('#txtCaptcha').val('');
}
