if (typeof(SFX) == "undefined") {
    var SFX = {}; //load the SFX var if we don't already have one.
}

SFX.modal = function () {
    var modal_stack = [];

    return {
        'init': function () {
            jQuery.facebox.settings.overlay = true;
            jQuery.facebox.settings.closeImage = '/images/facebox/closelabel.gif';
            jQuery.facebox.settings.loadingImage = '/images/facebox/loading.gif';

            jQuery(document).bind('close.facebox', function() {
                    modal_stack = [];
                    });
            // Useful for non form modal windows, like screenshots
            jQuery(document).ready(function(jQuery) {
                    jQuery('a[rel*=facebox]').facebox() 
                    })
        },

        'modal_box': function (a_href) {
            var modal_param = '?modal=1';
            
            if (a_href.href.match(/\?/)) {
                modal_param = '&modal=1';
            }
            jQuery.facebox.loading();
            jQuery.ajax({url: a_href.href + modal_param, success:SFX.modal.modal_ajax_load_success, cache: false});
            jQuery("#facebox .content").prepend("<h3 class='modal_titlebar'>" + a_href.title + "</h3>");
            modal_stack.push(a_href);
            return false;
        },

        'modal_ajax_load_success': function(data, textStatus) {
            jQuery("#top_feedback").hide();
            jQuery.facebox(data);
            // If <form rel="direct", don't force the response into a new facebook, let it go through
            jQuery("#facebox .content form[rel!='direct']").submit(function() {
                    return SFX.modal.modal_submit(this);
                    });
            if (modal_stack.length > 1) {
                jQuery("#facebox .footer").prepend("<a class='facebox_back_button leftarw' href='#' onclick='return SFX.modal.modal_back();'>Back</a> &nbsp; ");
            } else {
                jQuery("#facebox .footer .facebox_back_button").remove();
            }
            return true;
        },

        'modal_submit': function(form) {
            var form_data = jQuery(form).serializeArray();
            jQuery.facebox.loading();
            form_data.push({name: 'post_changes', value: 'Submit'});
            jQuery.ajax({url: form.action, type: 'POST', data: form_data, success: SFX.modal.modal_ajax_load_success, cache: false});
            return false;
        },

        'modal_back': function() {
            modal_stack.pop();
            SFX.modal.modal_box(modal_stack.pop());
        }
    };
}();

jQuery(function() {
        SFX.modal.init();
        });
