$(function()
{
    var fancyboxWrapper = $("#fancybox-outer");
    var fancyboxContent = $("#fancybox-inner");
    var contactLinks    = $(contactLinkPattern);
    
    var displayOptions = {
        overlayOpacity: 0.5,
        overlayColor: '#000',
        padding: 0,
        fadeIn: 200,
        speedIn: 200,
        speedOut: 100,
        scrolling: 'no',
        autoScale: false
    };
    
    var savedContent;
    
    $(contactLinkPattern).click(function(e)
    {
        //Skip our behaviour if any modifier keys were pressed
        if (e.metaKey || e.altKey || e.shiftKey || e.ctrlKey) return;
        
        if (savedContent)
        {
            //Use the already-loaded data if present, so that the user's form input is persisted
            //Also hide any errors, so that the form looks fresh
            $.fancybox($.extend({
                content: savedContent,
                onComplete: prepareContent
            }, displayOptions));
        }
        else
        {
            //Otherwise, fetch a new contact form from the Ajax API (which will be saved for later use)
            $.fancybox($.extend({
                href: contactAPIURL,
                onComplete: prepareContent
            }, displayOptions));
        }
        return false;
    });
    
    function prepareContent()
    {
        slideIn(); //Ensure the content is visible
        var content     = fancyboxContent.children();
        var contactForm = content.find('form');
        
        if (contactForm.length)
        {
            //Persist the content so that we preserve the user's input in the form
            savedContent = content;
            contactForm.submit(formSubmit);
        }
        else
        {
            //If no form was present in the content, then assume it's a success/error message and don't persist it
            //(This way, we fetch another form next time the lightbox appears rather than caching the content.)
            //Also make it disappear when clicked on!
            content.click(function() { $.fancybox.close(); });
            savedContent = null;
        }
    }
    
    function formSubmit()
    {
        slideAway();
        $.ajax({
            type: "POST",
            cache: false,
            url: contactAPIURL,
            data: $(this).serializeArray(),
            success: showResponse
        });
        //TODO: add failure handling
        
        return false;
    }
    
    function stripErrors()
    {
        $('label.has-errors', fancyboxContent).removeClass('has-errors');
        $('em.error', fancyboxContent).remove();
    }
    
    function slideAway()
    {
        fancyboxWrapper.animate({ top: '-250%', opacity: 'hide' }, 500, 'swing');
    }
    
    function slideIn()
    {
        fancyboxWrapper.animate({ top: '0', opacity: 'show' }, 500, 'easeOutBounce');
    }
    
    function showResponse(returnedContent)
    {
        var options = $.extend({}, displayOptions, {
            changeSpeed: 0, //Don't bother doing a fade transition offscreen
            content:    returnedContent,
            onComplete: prepareContent
        });
        
        $.fancybox(options);
    }
});