function openPopup(url) {
	$(document).keydown(function(e) {
	    if (e.keyCode == 27) {
	        closePopup();
	        e.preventDefault();
	    }
	});
	$('#popup-overlay').click(function(e) {
		closePopup();
        e.preventDefault();
	});
	
	$('#popup-overlay').css('height', $(document).height() + 'px');
	$('#popup-window').css('top', (window.pageYOffset + Math.round((window.innerHeight - $('#popup-window').height()) / 2)) + 'px');
	$('#popup-overlay, #popup-window').fadeIn();
	
	$.get(url, function(data) {
		fillPopup(data);
	}, 'html');
}

function fillPopup(htmlData) {
	$('#popup-window').scrollTop(0).scrollLeft(0);
	$('#popup-window .container').html(htmlData);
	$('#popup-window .loading').fadeOut(function() {
		$('#popup-window .container').fadeIn();
	});
	
	$('#popup-window form').submit(function(e) {
		var form = this;
		$('#popup-window .container').fadeOut(function() {
			$('#popup-window .loading').fadeIn(function() {
				$.post($(form).attr('action'), $(form).serializeArray(), function(data) {
					fillPopup(data);
				});
			});
		});
		e.preventDefault();
	});
}

function closePopup() {
	$(document).unbind('keydown');
	$('#popup-overlay').unbind('click');
	$('#popup-overlay, #popup-window').fadeOut(function() {
		$('#popup-window .loading').show();
		$('#popup-window .container').html('');
	});
}
