/**
 * Dialog v 1.0
 * QQ:50016724 leo
 *
 *回调函数：
 *afterShow:function(){alert('before show')};               //窗口打开后
 *afterClose:....											//窗口隐藏后
 *
 *窗口类型：
 *type:success,fail,loading
 *
 *
 *最近修改日期：2011-8-12 16:11
 */
(function($){
	function Dialog(content, options)
	{
		var defaults = { // 默认值。 
			tip:'',       	// 提示文本 
			showTip:true,     // 是否显示标题栏。
			closeText:'确定', 	// 关闭按钮文字，若不想显示关闭按钮请通过CSS设置其display为none 
			draggable:false,     // 是否移动 
			modal:true,         // 是否出现遮罩层 
			center:true,        // 是否居中。 
			fixed:true,         // 是否跟随页面滚动。
			time:0,             // 自动关闭时间，为0表示不会自动关闭。 
			id:false,		    // 对话框的id，若为false，则自动产生一个唯一id。
			width:250,			// 对话框宽度
			height:'auto',		// 对话框高度
			type:'normal'       // 对话框的几种形式
		};
		var options = $.extend(defaults, options);
		options.id = options.id ? options.id : 'dialog-' + Dialog.__count; // 唯一ID
		var overlayId = options.id + '-overlay'; // 遮罩层ID
		var timeId = null;  // 自动关闭计时器
		var isShow = false;
		var isIe = $.browser.msie;
		var isIe6= $.browser.msie && ($.browser.version == "6.0");
	
		/* 对话框的布局及标题内容。*/
		var barHtml = !options.showTip ? '' :
			'<div class="bar"><span class="tip">' + options.tip + '</span><input type="button" value="' + options.closeText + '" class="close"  /></div>';
		var dialog = $('<div id="' + options.id + '" class="dialog" style="height:' + options.height + 'px; width:' + options.width + 'px;"><div class="content"></div>'+barHtml+'</div>').hide();
		$('body').append(dialog);
	
	
		/**
		 * 重置对话框的位置。
		 *
		 * 主要是在需要居中的时候，每次加载完内容，都要重新定位
		 *
		 * @return void
		 */
		var resetPos = function()
		{
			/* 是否需要居中定位，必需在已经知道了dialog元素大小的情况下，才能正确居中，也就是要先设置dialog的内容。 */
			if(options.center)
			{
				var left = ($(window).width() - dialog.width()) / 2;
				var top = ($(window).height() - dialog.height()) / 2;
				if(!isIe6 && options.fixed)
				{   
					if(content.type == 'html' && isIe){
						dialog.css({top:top+$(document).scrollTop(),left:left+$(document).scrollLeft()})
					}else{
						dialog.css({top:top,left:left}); 
					}
				}
				else
				{   
					dialog.css({top:top+$(document).scrollTop(),left:left+$(document).scrollLeft()})
				}
			}
		}
	
		/**
		 * 初始化位置及一些事件函数。
		 *
		 */
		var init = function()
		{
			if(options.modal)
			{
				$('body').append('<div id="' + overlayId + '" class="dialog-overlay"></div>');
				$('#' + overlayId).css({'left':0, 'top':0,
						/*'width':$(document).width(),*/
						'width':'100%',
						/*'height':'100%',*/
						'height':$(document).height(),
						'z-index':++Dialog.__zindex,
						'position':'absolute'})
					.hide();
			}
	
			dialog.css({'z-index':++Dialog.__zindex, 'position':options.fixed ? 'fixed' : 'absolute'});
			
			
			/*  IE 兼容fixed代码 */
			if(isIe && options.fixed && content.type == 'html' || isIe6)
			{
				dialog.css('position','absolute');
				resetPos();
				var top = parseInt(dialog.css('top')) - $(document).scrollTop();
				var left = parseInt(dialog.css('left')) - $(document).scrollLeft();
				$(window).scroll(function(){
					dialog.css({'top':$(document).scrollTop() + top,'left':$(document).scrollLeft() + left});
				});
			}
	
			/* 以下代码处理框体是否可以移动 */
			var mouse={x:0,y:0};
			function moveDialog(event)
			{
				var e = window.event || event;
				var top = parseInt(dialog.css('top')) + (e.clientY - mouse.y);
				var left = parseInt(dialog.css('left')) + (e.clientX - mouse.x);
				dialog.css({top:top,left:left});
				mouse.x = e.clientX;
				mouse.y = e.clientY;
			};
			dialog.find('.bar').mousedown(function(event){
				if(!options.draggable){  return; }
				dialog.find('.bar').css('cursor','move')
				var e = window.event || event;
				mouse.x = e.clientX;
				mouse.y = e.clientY;
				$(document).bind('mousemove',moveDialog);
			});
			$(document).mouseup(function(event){
				$(document).unbind('mousemove', moveDialog);
			});
	
			/* 绑定一些相关事件。 */
			dialog.find('.close,.sub').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});
			dialog.find('.close').bind('click', this.close);
			dialog.bind('mousedown', function(){  dialog.css('z-index', ++Dialog.__zindex); });
			resetPos();
			// 自动关闭 
			if(0 != options.time){  timeId = setTimeout(this.close, options.time);}
		}
	
	
		/**
		 * 设置对话框的内容。 
		 *
		 */
		this.setContent = function(c)
		{
			var div = dialog.find('.content');
			if('object' == typeof(c))
			{
				switch(c.type.toLowerCase())
				{
				case 'html': 
					dialog.html(c.html);
					break;
				case 'success': 
					dialog.html('<div class="success">'+c.text+'</div>' + barHtml);
					break;
				case 'fail':
					dialog.html('<div class="fail">'+c.text+'</div>' + barHtml);
					break;
				case 'loading':
					dialog.html('<div class="loading_box"><img src="'+c.src+'" /><span class="loading">'+c.text+'</span></div>');
					break;
				case 'reply':
					var _html = '<div class="reply"><p class="reply_t">回复标题： <input type="text" onfocus="$(this).val(\'\').css(\'color\',\'#333\')" value="-请输入回复标题-" /></p><p class="reply_u">回复用户： <span id="reply_userName">'+c.uesrName+'</span></p><p class="reply_text"><textarea></textarea></p></div><div class="bar"><input type="button" class="close" value="取消"> <input type="button" class="sub" value="确定" onclick="$.Dialogs.close()"></div>'
					dialog.html(_html);
					break;
				}
			}
			else
			{   div.html(c); }
			init.call(this);
		}
	
		/**
		 * 显示对话框
		 */
		this.show = function()
		{
			resetPos();
			if(undefined != options.beforeShow && !options.beforeShow())
			{   return;  }
	
			/**
			 * 获得某一元素的透明度。IE从滤境中获得。
			 *
			 * @return float
			 */
			var getOpacity = function(id)
			{
				if(!isIe)
				{   return $('#' + id).css('opacity');    }
	
				var el = document.getElementById(id);
				return (undefined != el
						&& undefined != el.filters
						&& undefined != el.filters.alpha
						&& undefined != el.filters.alpha.opacity)
					? el.filters.alpha.opacity / 100 : 1;
			}
			/* 是否显示背景遮罩层 */
			if(options.modal)
			var op = getOpacity(overlayId);
			{   $('#' + overlayId).css({display:'block',opacity:0}).animate({opacity:op},'fast');   }
			
			dialog.fadeIn('fast',function(){
				if(undefined != options.afterShow){   options.afterShow(); }
				isShow = true;
				
			});
			// 自动关闭 
			if(0 != options.time){  timeId = setTimeout(this.close, options.time);    }
			dialog.find('.close').focus();
			dialog.find('.close').blur();
		}
	
	
		/**
		 * 隐藏对话框。但并不取消窗口内容。
		 */
		this.hide = function()
		{
			if(!isShow){ return; }
	
			if(undefined != options.beforeHide && !options.beforeHide())
			{   return;  }
	
			dialog.hide('',function(){
				if(undefined != options.afterHide){   options.afterHide(); }
			});
			if(options.modal)
			{$('#' + overlayId).hide();}
	
			isShow = false;
		}
	
		/**
		 * 关闭对话框 
		 *
		 * @return void
		 */
		this.close = function()
		{
			if(undefined != options.beforeClose && !options.beforeClose())
			{   return;  }
			dialog.fadeOut('fast', function(){
				$(this).remove();
				isShow = false;
				if(undefined != options.afterClose){   options.afterClose(); }
			});
			if(options.modal)
			{   $('#'+overlayId).fadeOut('fast',function(){$(this).remove()}); }
			clearTimeout(timeId);
		}
	
		this.setContent(content);
		
		Dialog.__count++;
		Dialog.__zindex++;
	}
	Dialog.__zindex = 500;
	Dialog.__count = 1;


	
	/*
	/jquery 实例化
	/
	*/
	var Dialogs = function() {
		var box;
		var isShow = false;
		this.open = function(content,options){
			if (typeof(options) == "undefined") {
				options = {};
			}
			box = new Dialog(content,options);
			box.show();
			isShow = true;
		}
		
		this.close = function(){
			if(isShow){
				box.close();
			}else{
				setTimeout(function(){if(isShow){box.close()}},200)
				}
		}
	}
	$.extend({Dialogs: new Dialogs()});	
	
})(jQuery)
