$(function () {
    function contact() {
        if ($("#contactForm").is(":hidden")) {
            $("#contactForm").slideDown("slow");
            $("#backgroundPopup").css({ "opacity": "0.7" });
            $("#backgroundPopup").fadeIn("slow");
        }
        else {
            $("#contactForm").slideUp("slow");
            $("#backgroundPopup").fadeOut("slow");
        }
    }

    $(".contact").click(function () { contact() });
    $("#backgroundPopup").click(function () { contact() });

    //only need force for IE6  
    $("#backgroundPopup").css({
        "height": document.documentElement.clientHeight
    });

    $('#showMessage').live('click', function () {
        $('#mailResponse').hide();
        $('#emailForm').fadeIn('slow');
        return false;
    });

    $('#emailForm').submit(function () {
        if ($(this).valid()) {
            $('#emailForm').hide();
            $('#loading').fadeIn('slow');

            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (response) {
                    $('#loading').hide();

                    if (response.status === 'success') {
                        $('#mailResponse div').html(
                            '<h3>Thank you!</h3><p>I will get back to you as soon as I can.</p>'
                        );
                        $('#mailResponse').fadeIn('slow');
                        setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 3000);
                    }
                    else if (response.status === 'spam') {
                        $('#mailResponse div').html(
                            '<p>Your message was rejected by our spam filter. Please remove any links or uncommon characters from your message and try again.</p>' +
                            '<a href="/" id="showMessage">Go back to message</a>'
                        );
                        $('#mailResponse').fadeIn('slow');
                    }
                    else if (response.status === 'error') {
                        $('#mailResponse div').html(
                            '<p>There was a problem sending your message. Please try again or email me at <a href="mailto:micahmcneely@gmail.com">micahmcneely@gmail.com</a></p>' +
                            '<a href="/" id="showMessage">Go back to message</a>'
                        );
                        $('#mailResponse').fadeIn('slow');
                    }
                },
                error: function (response) {
                    $('#loading').hide();
                    $('#emailForm').show();
                }
            });
        }
        return false;
    });
});
