﻿jQuery.fn.center = function () {
    this.makeAbsolute(true);
    //this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

$.fn.makeAbsolute = function (rebase) {
    return this.each(function () {
        var el = $(this);
        var pos = el.position();
        el.css({ position: "absolute",
            marginLeft: 0, marginTop: 0,
            top: pos.top, left: pos.left
        });
        if (rebase)
            el.remove().appendTo("body");
    });
}

var modalWindow = {
    parent: "body",
    windowId: null,
    content: null,
    left: null,
    top: null,
    width: null,
    height: null,
    hide: function () {
        $(".modal-window").css("display", "none");
        $(".modal-overlay").remove();
    },
    close: function () {
        $(".modal-window").remove();
        $(".modal-overlay").remove();
    },
    closeWithRefresh: function () {
        $(".modal-window").remove();
        setTimeout(delayedReload, 500);
    },
    open: function () {
        var modal = "";
        modal += "<div class=\"modal-overlay\"><img style=\"z-index: 1000;\" id=\"ajax-loader\" src=\"/images/ajax-loader.gif\" /></div>";
        modal += "<script>$('#ajax-loader').center();</script>";
        modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"display:none;left:" + this.left + ";top:" + this.top + ";width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
        modal += this.content;
        modal += "</div>";

        $(this.parent).append(modal);

        $(".modal-overlay").click(function () { modalWindow.close(); });
    }
};

function delayedReload() {
    window.location.reload();
}

function OnWindowIsLoad() {
    $(".modal-window").css("display", "");
}

var openMyModal = function (source, left, top, width, height) {
    modalWindow.windowId = "myModal";
    if (left) { modalWindow.left = left; } else { modalWindow.left = '50%'; }
    if (top) { modalWindow.top = top; } else { modalWindow.top = '50%'; }
    modalWindow.width = width;
    modalWindow.height = height; 
    if (source.length > 0) modalWindow.content = "<iframe width='100%' height='100%' frameborder='0' allowtransparency='false' scrolling='auto' src='" + source + "' onload='OnWindowIsLoad();'></iframe>";
    else modalWindow.content = '';
    modalWindow.open();
};

