MVD = {};

(function ($) {

    MVD.Popup = function (content, callback) {    
        this.cont = content; 
        this.callback = callback;
        this.init();
    }
    
    function getBG() {
        var bg = MVD.Popup.prototype.bg;
        if (!bg) {
            bg = $("<div></div>").addClass("popupBG");
            $("body").append(bg);
            MVD.Popup.prototype.bg = bg;            
        }
        return bg;
    }
    
    $.extend(MVD.Popup.prototype, {
        view : false,        
    
        open : function () {
            if (!this.view) {
                this.view = true;          
                this.center();
                getBG().css("opacity", "0.7").fadeIn("slow");
                if (this.callback) { 
                    this.callback(); 
                }
                this.cont.slideDown("slow");
                $(window).bind("scroll resize", this.recenter);
            }
        },
        
        close : function () {
            if (this.view) {
                this.view = false;
                getBG().fadeOut("slow");
                this.cont.fadeOut("slow");
                $(window).unbind("scroll resize", this.recenter);
            }
        },
        
        center : function () {
            var w = $(window);
            getBG().css({"height": $(document).height(), 
                         "width": w.width()});
                                     
            var sx = w.scrollLeft();
            var sy = w.scrollTop();
                                 
            var winH = w.height();  
            var winW = w.width();
            var pHeight = this.cont.height();
            var pWidth = this.cont.width();
            
            this.cont.css({
                "position": "absolute",
                "top": sy + (winH - pHeight)/2,
                "left": sx + (winW - pWidth)/2
            });
        },
        
        init : function () {            
            var that = this;    
            var closefn = function () { that.close(); return false; };            
            $(document).keypress(function(e) {
                if (!e) { e = event };
                if(e.keyCode == 27) {
                    closefn();
                }
            });
            getBG().click(closefn);
            $('.btnClose', this.cont).click(closefn);
            this.recenter = function () { that.center(); };            
        }
        
    });

}) (jQuery);