$(document).ready(function() {
    var validator = $('#contact-form').validate({
        rules: {
            name: "required",
            email: {
                required: true,
                email: true
            },
            message: "required",
            code: "required"
        },
        messages: {
            name: "* Name required",
            email: {
                required: "* Email required",
                email: "* Invalid email address"
            },
            message: "<br/>* Message required",
            code: "* Code required"
        },
        submitHandler: function() {
            $.post("/contact/send",
                {
                    name: $('#name').val(),
                    email: $('#email').val(),
                    message: $('#message').val(),
                    code: $('#code').val(),
                    randomID: $('#randomID').val()
                },
                function(data) {
                    $('#randomID').val(data["randomID"]);
                    $('#captcha-image').attr("src", "/contact/captcha?id=" + data["randomID"]);

                    if (data["sent"] == true) {
                        $('#code-error').css("display", "none");
                        closeContact();
                        showThanks();
                        resetContactForm(validator);
                    } else {
                        $('#code-error').text("* " + data["message"]);
                        $('#code-error').css("display", "inline");
                    }
                }
            );
        }
    });

    $('#contact-modal').jqm({
        modal: false,
        overlay: 60
    });

    $('#pictures-modal').jqm({
        modal: false,
        overlay: 60
    });

    $('#thanks-modal').jqm({
        modal: false,
        overlay: 60
    });

});

function showPictures() {
    $('#pictures-modal').center();
    $('#pictures-modal').jqmShow();
}

function closePictures() {
    $('#pictures-modal').jqmHide();
}

function showContact() {
    $('#contact-modal').center();
    $('#contact-modal').jqmShow();
}

function closeContact() {
    $('#contact-modal').jqmHide();
}

function showThanks() {
    $('#thanks-modal').center();
    $('#thanks-modal').jqmShow();
}

function closeThanks() {
    $('#thanks-modal').jqmHide();
}

function resetContactForm(validator) {
    $('#name').val("");
    $('#email').val("");
    $('#message').val("");
    $('#code').val("");

    if (validator) {
        validator.resetForm();
    }
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}






