String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

function Popup() {
	this.recount_top_left = function () {
		var overlay = $(".simple_overlay");
		var bg = $(".simple_overlay_bg");

		var oWidth = $(".simple_overlay").outerWidth({margin:true});
		var oHeight = $(".simple_overlay").outerHeight({margin:true});
		
		left = Math.max((w.width() - oWidth) / 2, 0);
		topp = Math.max((w.height() - oHeight) / 2, 0);
		
		topp += w.scrollTop();
		left += w.scrollLeft();
		
		overlay.css({top: topp, left: left, position: 'absolute'});
	}
	this.show = function (header, text) {
		w = $(window);
		t = this;
		html = '<div class="simple_overlay_bg" onclick="popup_close()"></div><div class="simple_overlay"><div class="header">{header}</div><div class="close" onclick="popup_close()"></div><div class="overlay-content">{content}</div></div>'
				.supplant({content: text, header: header});
				
		$("body").append(html);
		
		$(".simple_overlay").ajaxComplete(function() {
			t.recount_top_left();
		});

		$(".simple_overlay_bg").css({height: $("body").height()}).show();
		this.recount_top_left();
		$(".simple_overlay").show();
	}
	this.show_loader = function() {
		$(".simple_overlay").css("background", "url('img/popup/ajax-loader.gif') no-repeat 50% 50% #fff");
	}
	
	this.hide_loader = function() {
		$(".simple_overlay").css("background", "url('img/popup/bg.png') repeat-x #fff");
	}
	
	this.change_content = function (content) {
        $(".overlay-content").html(content);
		this.recount_top_left();
	}
	
	this.show_url = function (header, url) {
		p = this;
		p.show(header, '');
		p.show_loader();
		$.get(url, function(data) {
			p.change_content(data);
			p.hide_loader();
		});
	}
}

function popup_close() {
	$(".simple_overlay").remove();
	$(".simple_overlay_bg").remove();
}

