/** Usage
<a href="/layout/ajax_reply.php" class="popup modal">弹出对话框 (Modal)</a>
<script type="text/javascript">
$(document).ready(function(){
	$('.popup').bind('click', function() {
		$.popUp($(this).attr('href'), {'closer':'关闭[x]','title':'弹出对话框','modal':$(this).attr('title')});
		return false;
	});
});
</script>
***/
// Author: Yu, Qiang <kevin@w3softwares.com>
(function($)
{
	$.fn.popUp = function(options)
	{
		var config = {
 			'title':null,
 			'modal': true
		};
		if (options) $.extend(config, options);
 		var popupStatus = 0;

		var popup_html = '<div id="ux-popup"><table cellspacing="0" cellpadding="0"><tr><td><div id="ux-popup-container">\n'+
			'<div id="ux-popup-title"><div id="ux-popup-closer">&nbsp;&nbsp;</div><h1>'+config.title+'</h1></div>\n'+
            '<div id="ux-popup-body">Loading ...</div></div></td></tr></table></div>';
 		//1. create popup dom with loading indicator in body
 		this.each(function() {
 			$(this).click(function() {
 				closePopup();
 				$('body').append(popup_html);
 				var popup = $('#ux-popup');
 				if (!config.modal && !$(this).hasClass('modal')) {
 					popup.css('background','none');
 				}
				if ($(this).attr('title')) {
					$('#ux-popup-title h1').html($(this).attr('title'));
				}
 				//2. loading content into popup and ajust popup position
 				$('#ux-popup-body').load($(this).attr('href'), null, centerPopup);
				//load popup
				loadPopup();
 				//4. binding event handlers
				$('#ux-popup-closer').click(function(){
					closePopup();
					return false;
				});
				//Press Escape event!
				$(document).keypress(function(e){
					if(e.keyCode==27 && popupStatus==1){
						closePopup();
					}
				});
				return false;
			});
		});
		return this;
 
		function clearPopup()
		{
			if (popupStatus) {
				$('#ux-popup').remove();
			}
			popupStatus = 0;
		}
		function loadPopup(){
			$('#ux-popup').fadeIn("slow");
			centerPopup();
		}
 
		//disabling popup with jQuery magic!
		function closePopup()
		{
			$('#ux-popup').fadeOut("slow", clearPopup);
		}
 
		//centering popup
		function centerPopup()
		{
			//request data for centering
 			popupStatus = 1;
			var windowHeight = $(window).height();
			var popupHeight = $('#ux-popup-body').height();
			//centering
			$('#ux-popup-container').css({
				'top': Math.max(0, windowHeight/2-popupHeight/2-80)
			});
			if ($('#ux-popup-container').height()>$(window).height()) {
				$('#ux-popup-container').height($(window).height()*.85);
			}
			if ($('#ux-popup-container').width()>$(window).width()) {
				$('#ux-popup-container').width($(window).width()*.85);
			}
			$('.popup-closer').click(function(){
				closePopup();
				return false;
			});
		}
	};
})(jQuery);

