$(function(){
    $(".newsletter-form .name").blur(function(){
        if (this.value == "") {
            this.value = "Name...";
        }
    });
    $(".newsletter-form .name").focus(function(){
        if (this.value == "Name...") {
            this.value = "";
        }
    });
    $(".newsletter-form .email").blur(function(){
        if (this.value == "") {
            this.value = "Email Address...";
        }
    });
    $(".newsletter-form .email").focus(function(){
        if (this.value == "Email Address...") {
            this.value = "";
        }
    });
    $("#subscribeBtn").click(function(){
    
        if (isValidName() && isValidEmail()) {
            $.post("submit_newsletter.php", {
                name: $(".newsletter-form .name").val(),
                email: $(".newsletter-form .email").val()
            }, function(data){
                if (data == "success") {
                    $(".newsletter-form .name").val("Name...");
                    $(".newsletter-form .email").val("Email Address...");
                    $(".confirmation div").html("Subscribtion<br>Successful");
					showConfirmation();
                }
                else {
				 	$(".confirmation div").html("Subscribtion failed.<br>Please try again.");
					showConfirmation();
                }
            });
        }
    });
});
function showConfirmation(){
    $(".confirmation").fadeIn("slow", function(){
        setTimeout(function(){
            $(".confirmation").fadeOut("slow");
        }, 2000);
    });
}

function isValidName(){
    if (($(".newsletter-form .name").val() == "Name...") || ($(".newsletter-form .name").val() == "")) {
        showError("name", "< Name Required");
        return false;
    }
    return true;
}

function isValidEmail(){
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (($(".newsletter-form .email").val() == "Email Address...") || ($(".newsletter-form .email").val() == "")) {
        showError("email", "< Email Required");
        return false;
    }
    if (filter.test($('.newsletter-form .email').val())) {
        return true;
    }
    else {
        showError("email", "< Invalid Email");
        return false;
    }
    return false;
}

function showError(id, msg){
    $("#" + id + "Error").html(msg);
    $("#" + id + "Error").fadeIn("slow", function(){
        setTimeout(function(){
            $("#" + id + "Error").fadeOut("slow");
        }, 2000);
    });
}

