﻿/*
    Written by Aaron of www.aaronpresley.net fame.

    This plugin is created to appease the .NET gods. It creates a modal in-place and doesn't remove
    and append the modal content to the end of the page, which breaks any and all JS references
    to the elements. Bummer.
    
    INSTRUCITONS!
    1) Include this here Javascript file on the page you wish to have Modal Madness
    2) Give your action link a class of "open_modal" and the href of the div you wish to open
    3) Give your modal div a class of .modal
    4) Try not to wet yourself

    EXAMPLE!
    <script type="text/javascript" src="location/modal_window.js"></script>
    <a href="#my_modal" class="open_modal">Open Modal</a>
    <div id="my_modal" style="display:none;">   
    Modal here, yo!
    </div>
*/

$(document).ready(function () {
    //add the screen to darken the background
    $('body').append('<div id="modal_screen" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;z-index:1100;background:transparent url(Admin/images/modal_screen.gif);"></div>');

    //traverse all modals on the page and add necessary CSS
    $('div.modal').each(function () {
        $(this)
            .css('z-index', '1200 !important')
            .css('position', 'absolute')
            .css('top', '100px');
    });

    //handle when modal loses focus
    $('#modal_screen,').click(function () { close_modal() });

    //handle when close button is clicked
    $('.close_modal').click(function () { close_modal() });

    //set modal button clicks
    $('.open_modal').click(function () {
        var to_open = $(this).attr('href');
        open_modal(to_open);
        return false;
    });
});


function open_modal(modal) {
    $('#modal_screen').show();
    $('.flash').hide();

    //Centering the modal horizontally
    var win_width = $('body').innerWidth();
    var win_horiz_center = win_width / 2;

    var modal_width = $(modal).width();
    var modal_horiz_center = modal_width / 2;

    var modal_horiz_pos = win_horiz_center - modal_horiz_center;


    //Centering the modal vertically
    var win_height = $(window).height();
    var win_vert_center = win_height / 2;

    var modal_height = $(modal).height();
    var modal_vert_center = modal_height / 2;

    var modal_vert_pos = win_vert_center - modal_vert_center;


    $(modal)
        .css('left', modal_horiz_pos)
        .css('top', modal_vert_pos)
        .show();

}

function close_modal() {
    $('#modal_screen').hide();
    $('div.modal').hide();
    $('.flash').show();
}
