﻿(function ($) {

    var methods = {

        buildWindow: function (id, contents, width, height) {

            $("body div").first().append(contents.replace("{id}", id));

            var marginTop = Math.floor(((height + 42) / 2) + 0.5) * -1;
            var marginLeft = Math.floor(((width + 42) / 2) + 0.5) * -1;

            $("." + id).css("width", (width + 42) + "px").css("height", (height + 42) + "px").css("margin-top", marginTop + "px").css("margin-left", marginLeft + "px");
            $("." + id + " .modal_inner").css("width", width + "px").css("height", height + "px");
            $("." + id + " .top").css("width", width + "px");
            $("." + id + " .bottom").css("width", width + "px");
        },

        showWindow: function (id, iframe, href) {

            if ($.browser.msie && (parseFloat($.browser.version) <= 7)) {
                $("#modal_overlay").css("background-color", "#555555").css("display", "block");
                $("." + id).css("background-color", "#FFFFFF").css("display", "block");
            } else {
                $("#modal_overlay").show("fade", 200, function () {
                    $("." + id).first().show("fade", 200);
                });
            }

            $("." + id + " .modal_inner").first().html(iframe.replace("{href}", href));
        }
    };

    $.fn.lightmediaModal = function (modalOptions) {

        modalOptions = $.extend({
            windowClass: "",
            width: 800,
            height: 600,
            iframeMarkup: "<iframe class='modal_iframe' src='{href}'></iframe>",
            overlayMarkup: "<div id='modal_overlay'><span>&nbsp;</span></div>",
            windowMarkup: "<div class='modal_window {id}'><div class='top_left'>&nbsp;</div><div class='top'>&nbsp;</div><div class='top_right'>&nbsp;</div><div class='modal_inner'></div><div class='bottom_left'>&nbsp;</div><div class='bottom'>&nbsp;</div><div class='bottom_right'>&nbsp;</div></div>"
        }, modalOptions);

        if ($("#modal_overlay").length <= 0) {
            $("body div").first().append(modalOptions.overlayMarkup);
        }

        methods.buildWindow("modal_" + modalOptions.windowClass, modalOptions.windowMarkup, modalOptions.width, modalOptions.height);

        this.each(function () {
            $(this).click(function (event) {
                event.preventDefault();
                methods.showWindow("modal_" + modalOptions.windowClass, modalOptions.iframeMarkup, $(this).attr("href"));
            });
        });

        return this;
    };

})(jQuery);
