
function pop_over(trigger_elements, html)
{
    var element = false;

    function open(parent_el)
    {
        if (element)
            return;

        element = $(html).appendTo(parent_el);

        element.find('input[type=button]').click(signup);
        element.find('input[type=text]').keypress(function(e)
        {
            if (e.which != 13)
                return;
            setTimeout(signup, 1);
        });

        focus();
    }

    function signup(email)
    {
        var email = element.find('input[type=text]').val();
        if (!email)
            return;
        button('Signing up...', true);
        $.ajax({
            url: '/subscribe',
            type: 'POST',
            data: { e: email },
            success: function()
            {
                button('Done!', true);
                setTimeout(close, 1000);
            },
            error: function()
            {
                button('Invalid address', true);
                setTimeout(function() { 
                    button('Sign up'); 
                    focus();
                }, 2000);
            }
        });
    }

    function focus()
    {
        element.find('input[type=text]').focus();
    }

    function button(text, disable)
    {
        element.find('input[type=button]')
            .attr('disabled',disable?'disabled':null).val(text);
    }

    function close()
    {
        if (!element)
            return;
        element.remove();
        element = false;
    }

    $(trigger_elements)
        .click(function()
    {
        if (!element)
            open(this);
        else
            close();
        return false;
    });
}

$(function()
{
    pop_over(
        '.topstrip .subscribe, .bottomstrip .subscribe, .bottommenu .subscribe',
        '<div class="subscribe-signup">'+
            'Enter your email to sign up to our newsletter: '+
            '<input type="text" /> <input type="button" value="Sign up" />'+
        '</div>'
    );
    pop_over(
        '.menubar a[name=visitors], .menubar a[name=video]',
        '<div class="coming-soon">'+
            'This section isn\'t ready just yet.<br />'+
            'Stay tuned - we\'re adding new content every day.'+
        '</div>'
    );
});

