function getEmailForm()
{
    return $("#non-customer-email");
}

function showResponse(message)
{
    clearResponse();
    getEmailForm().find('h3').after('<p class="response-message">'+message+'</p>');
    $.fancybox.resize();
}

function clearEmailForm()
{
    getEmailForm().find('input').val('');
}

function clearResponse()
{
    getResponse().remove();
}

function getResponse()
{
    return getEmailForm().find('.response-message');
}

function errorMessage(errors)
{
    var message = 'Please correct the following errors: ';
    var sep = "";
    for (var err in errors) {
         message = message + sep + errors[err];
         sep = ", ";
    }
    return message;
}

function nonCustomerEmailSuccess(response)
{
    if (response['success']) {
        clearEmailForm();
        var form = getEmailForm();
        form.find('.form-fields').hide();
        form.find('.success-message').show();
        $.fancybox.resize();
    }
    else {
        showResponse(errorMessage(response['errors']));
    }
}


jQuery(function(){

    /* Non-customer Email Lightbox */
    $("a[href='#non-customer-email']").fancybox({
        'autoSize': true,
        'centerOnScroll' : true,
        'onClosed' : function() { 
            clearEmailForm();
            clearResponse();
            getEmailForm().find('.form-fields').show();
            getEmailForm().find('.success-message').hide();
        },
        'overlayColor' : '#000',
        'overlayOpacity' : 0.75,
        'padding' : 0,
        'scrolling' : true,
        'showCloseButton' : false,
        'titleShow' : false
    });
    getEmailForm().ajaxForm({
        'beforeSubmit': clearResponse,
        'success' : nonCustomerEmailSuccess,
        'dataType' : 'json'
    });
    getEmailForm().find('.success-message button').click(function(){
        $.fancybox.close();
        return false;
    });
    getEmailForm().find('.form-fields a.cancel').click(function(){
        $.fancybox.close();
        return false;
    });

});

