Shadowbox.init({
    players: [ 'html', 'img', 'iframe' ],
    enableKeys: false,
});

function load_modal_content(url, iframe, title) { // title will be overridden by ajax response if not an iframe
    if (iframe) {
        Shadowbox.open({
            content: url,
            title:   title,
            player:  'iframe',
        });
    } else {
        new Ajax.Request(url, {
            method: 'get',
            onException: function(transport) { content = build_error_message(); },
            onFailure:   function(transport) { content = build_error_message(); },
            onSuccess:   function(transport) { content = transport.responseText; },
            onComplete:  function(transport) { show_modal_window(content, transport); },
        });
    }
}

function submit_modal_form(form) {
    form.request({
        onException: function(transport) { content = build_error_message(); },
        onFailure:   function(transport) { content = build_error_message(); },
        onSuccess:   function(transport) { content = transport.responseText; },
        onComplete:  function(transport) { show_modal_window(content, transport); },
    });
}

function show_modal_window(content, transport) {
    var json = transport.headerJSON;
    var title = null;
    var redirect = null;
    
    if (json) {
        title    = json['title'];
        redirect = json['redirect'];
    }
    
    if (redirect) {
        window.location = redirect;
    }
    
    Shadowbox.open({
        title:   title,
        content: content,
        player:  'html',
    });
}

function build_error_message() {
    html  = '<div class="si-modal-window si-modal-window-error">';
    html += '<p>Sorry, there has been an error while trying to retrieve content from the server.</p>';
    html += '<p>Please try again shortly or contact Technical Support if the problem continues.</p>';
    html += '<p><a href="' + site_url('') + '" onclick="event.stop(); Shadowbox.close();">Close</a></p>';
    html += '</div>';
    return html;
}
