(function($){
/*
 * @author denisdeng 
 * emmail dexibe@gmail.com || denisdeng@jobkoo.com
 * $Version: 2010.3.5 1.0
 *  $.Popup function
 *  @requires: jquery-1.3.2.min.js
			   popup class
 *  If an options Object is provided, the following attributes are supported:
 *
 *  overlayClass:The className of mask of popup.
 *  			 default:'overlay'
 *  popupShadowClass:The of className of popup's shadow.
 *               default:'popupShadow'
 *  overlayOpcity:The opcity of mask of popup.
 *               default:0.3
 *  shadowOpcity:The opcity of popup's shadow.
 *               default: 0.4
 *  zIndex:The zIndex of mask of popup.
 *            	 default:6000
 *  width:The width of popup.
 *               default: 400
 *  height:The height of popup.
 *               default:'auto'
 *  shadowOffset: The offset of popup's shadow.
 *				 default:8
 *  oBind: Boolean flag indicating whether to bind event to the  mask of popup.
 				 default:true
 *  shadowIsClone: whether to clone the shadow;
 				default:false
 *  overlayIsClone: whether to clone the overlay;
 				default:false
 *  isEscAndEnter:Whether to support the Esc and Enter keys ( press Esc key to hide 
				  the popup and press Enter key to submit the popup);
 				default:false
 *  popupClass: The className of popup.
 				 default:'popup'
 *  delay: The milliseconds to display the popup
 				 default:50				 
*/		  
$.Popup = function(obj,options){
	var settings = {
			overlayClass:'overlay',
			popupShadowClass:'popupShadow',
			overlayOpcity:0.3,//定义遮罩的透明度
			shadowOpcity:0.4,//定义阴影的透明度
			zIndex:6000,//定义z轴
			width:400,//定义宽度
			height:'auto',//定义高度
			shadowOffset:5,//定义阴影的偏移量
			oBind:true,//是否给遮罩层绑定click事件
			overlayIsClone:false,
			isEscAndEnter:true,
			iframeClone:true,
			shadowIsClone:false,
			popupClass:'popup',//设置弹出层的class
			delay:50
	   }
	if(options) settings = $.extend(settings, options);
	if($(obj).size() == 0){
		alert('对象不存在!');	
	}else{
		if(!obj.popup){
			obj.popup = new popup($(obj),settings);
		}
		return obj.popup;
	}
}
/*
 *  $.Message function
 *  @requires: jquery-1.3.2.min.js
			   $.Popup function
			   message class
	If an options Object is provided, the following attributes are supported:
 *
 *  title:The title of message.
 *  			 default:''
 *  content:The content of message.
 *               default: popupShadow
 *  btnCancel:Boolean flag indicating whether to show the cancel of button.
 *               default:false
 *  btnSure:Boolean flag indicating whether to show the submit of button.
 *               default:true
 *  msgClass:The className of message.
 *            	 default:dialog
 *  msgConClass:The className of message's content .
 *               default: msgCon
 *  msgFootClass:The className of message's footer .
 *               default:''
 *  width: The width of message.
 *				 default:300
 *  submitFunc:The function which is called when to click the btnSubmit.
 				 default:null
 *  resetFunc:The function which is called when to click the btnSure.
 				 default:null				 
*/
$.Message = function(options){
	var settings = {
			title:'',
			content:'',
			btnCancel:false,
			btnSure:true,
			msgClass:'dialog',
			msgConClass:'msgCon',
			btnCancelTxt:'取消',
			btnSureTxt:'确定',
			msgFootClass:'',
			width:300,
			//overlayIsClone:true,
			//shadowIsClone:true,
			submitFunc:null,
			resetFunc:null,
			closeFunc:null
	   }
	if(options) settings = $.extend(settings, options);
	var msg = new message(settings);
	var obj = msg.getObj();
	if($(obj).html() == null){
		alert('对象不存在!');	
	}else{
		return $.Popup($(obj),settings);
	}
}
/*
 *  $.Msg global object
 *  	overlay:The object;
 *  	popupShadow:The object; 
 *  	iframe:The object;  
 *  	ie6:Boolean; 
 *  	ie:Boolean;  
 */
$.Msg = {
	overlay:$("<div></div>").css({width:"100%",height:"100%",left:0,top:0}).hide(),
	popupShadow:$("<div></div>").hide(),
	iframe:$('<iframe src="javascript:false;" class="jqM"></iframe>').css({opacity:0}),
	ie6:$.browser.msie&&($.browser.version == "6.0"),
	ie:$.browser.msie,
	NUM:0//存储弹出层的数量;
}
/*
 * message class
 */
function message(options){
	this.msgHeader = $('<div class="popHeader"><a href="#" class="popClose close float-right"><i>close</i></a><h4></h4></div>');
	this.msgBody = $('<div class="popBody"></div>');
	this.msgFooter = $('<div class="popFooter"><a class="btnSubmit submit"><span>确定</span></a>&nbsp;&nbsp;<a class="btnCancel close"><span>取消</span></a></div>');
	this.options = options;
	this.init();
}
message.prototype = {
	init:function(){
		var self = this;
		this.obj = $("<div></div>");
		var header = $('h4', this.msgHeader).empty().append(this.options.title);
		//创建隐藏的文本框,以便弹出时使弹出层获得焦点;
		this.hiddenBtn = $("<input class='popup-hidden-btn' type='text' />").css({"position":'absolute',"left":'-9999px'});
		this.msgHeader.append(header);
		this.msgBody.addClass(this.options.msgConClass).empty();
		this.msgFooter.addClass(this.options.msgFootClass);
		var btnSubmit = $('a.submit',this.msgFooter);
		//设置提交按钮文本；
		$('span',btnSubmit).text(this.options.btnSureTxt);
		var btnReset = $('a.close',this.msgFooter);
		//设置取消按钮文本；		
		$('span',btnReset).text(this.options.btnCancelTxt);
		var hiddeClose = $('a.close',this.msgHeader);//取得消息框头部的关闭按钮;
		if(!this.options.btnCancel){
				btnReset.hide();
		};
		if(!this.options.btnSure){
				btnSubmit.hide();
		};
		if(this.options.btnSure){
			btnSubmit.bind('click',function(e){
					//默认触发关闭事件，当有提交函数时，执行提交函数
					//console.log(hiddeClose.size());
					$.isFunction(self.options.submitFunc) ?	self.options.submitFunc(btnSubmit) : hiddeClose.trigger('click');
					e.preventDefault();
			})
		};
		if(this.options.btnCancel){
			if($.isFunction(this.options.resetFunc)){
						btnReset.bind('click',function(e){
								self.options.resetFunc(btnReset);
								e.preventDefault();								
						})
			}
		};
		this.msgBody.append(this.options.content);
		this.msgBody.append(this.hiddenBtn);
		this.obj.append(this.msgHeader).append(this.msgBody).append(this.msgFooter);
		this.obj.addClass(this.options.msgClass).appendTo("body").hide();
	},
	getObj:function(){
		return this.obj;
	}
}
/*
 * popup class
 */
function popup(obj,options){
	this.popup = obj;
	this.options = options;
	this.shadowOffset = parseInt(options.shadowOffset);
	this.btnClose = $('a.close',options.obj);
	this.btnSubmit = $('.btnSubmit',options.obj);
	this.hiddenBtn = $('.popup-hidden-btn',options.obj);
	this.init();
	this.isShow = false;
	this.isEscAndEnter = options.isEscAndEnter;
}
popup.prototype = {
	init:function(){
		var self = this;
		this.ie = $.browser.msie;
		this.overlay =  this.options.overlayIsClone ? $($.Msg.overlay).clone() : $.Msg.overlay;
		this.iframe = this.options.iframeClone ? $($.Msg.iframe).clone() : $.Msg.iframe;
		this.maxWidth = Math.max($(document.body).width(),$(window).width());
		this.maxHeight = Math.max($(document.body).height(),$(window).height());
		this.overlay.addClass(this.options.overlayClass).css({opacity:this.options.overlayOpcity,zIndex:this.options.zIndex}).appendTo("body");
		if($.Msg.ie){
			this.overlay.css({'width':this.maxWidth,'height':this.maxHeight});
		}
		if($.Msg.ie6){
			this.overlay.prepend(this.iframe);
		}
		this.popup.addClass(this.options.popupClass).css({zIndex:this.options.zIndex + 2,'width':this.options.width,'height':this.options.height}).hide();
		if(this.options.height == 'auto'){
			this.options.height = $(this.popup).outerHeight();
		};
		this.popupShadow = this.options.shadowIsClone ? $($.Msg.popupShadow).clone() : $.Msg.popupShadow;
		this.popupShadow.addClass(this.options.popupShadowClass).css({zIndex:this.options.zIndex + 1,opacity:this.options.shadowOpcity}).appendTo('body');
		this.repaint();
	},
	show:function(){
		var self = this;
		var len = arguments.length;
		if(len >= 1){
			var args = Array.prototype.slice.call(arguments);
			var func = args.shift();
			if(!$.isFunction(func)){
				alert('请检查第一个参数是否为函数对象！');	
			};
		};
		//$('body').css({'min-height':this.popup.outerHeight() + 40});
		//if($.Msg.ie){
			//$('body').css({'height':this.popup.outerHeight() + 40});
		//};
		this.overlay.fadeIn(self.options.delay,function(){
	    	self.localizeWin(func,args);
		});
		if(this.ie){
			$(window).bind('resize',function(e){self.localizeWin(func,args);});
			$(window).bind('scroll',function(){self.localizeWin(func,args);});
			setTimeout(function(){
									$(window).trigger("scroll");
								},100);
		};
		if(this.options.oBind ){
			$(this.overlay).bind('click',function(){
				self.hide();
				//self.overlay.data("hasBind",true);
			})
		};
		//为每个关闭按钮绑定click事件;
		$(this.btnClose).each(function(){
			   if(!$(this).data("hasBind")){
					$(this).bind('click',function(e){
						//是否有关闭事件调用函数;
						if(self.options.closeFunc !== null && $.isFunction(self.options.closeFunc)){
							self.options.closeFunc();
						};
						self.hide();
						$(this).data("hasBind",true);
						e.preventDefault();	
					});
			   }
		});
		$.Msg[$.Msg.NUM] = this;
		$.Msg.NUM++;
	},
	localizeWin:function(func,args){
		var self = this;
		var maxWidth = Math.max(document.body.scrollWidth,$(window).width());
		var maxHeight = Math.max(document.body.scrollHeight,$(window).height());
		//alert(this.ie);
		var h = $(this.popup).data('liveH') ? $(this.popup).data('liveH') : this.options.height;
		if(!this.ie){
			var popStyle = {
					'margin-left': - this.options.width/2,
					'margin-top': - h/2
			};
			var popShadowStyle = {
					'margin-left': - this.options.width/2 - self.shadowOffset ,
					'margin-top': - h/2- self.shadowOffset,
					'width':this.options.width + (this.shadowOffset)*2,
					'height':h + (this.shadowOffset)*2
				
			}
	  	}else{
			var left = - this.options.width/2 + $(window).scrollLeft();
			var top = - h/2 + $(window).scrollTop();
			var popStyle = {
					'margin-left': left,
					'margin-top': top
			};
			var popShadowStyle = {
					'margin-left': left - this.shadowOffset,
					'margin-top': top- this.shadowOffset,
					'width':this.options.width + (this.shadowOffset)*2,
					'height':h + (this.shadowOffset)*2
			}
		    this.overlay.css({'width':maxWidth,'height':maxHeight});
		};
		//延时显示弹出框和阴影;
		setTimeout(function(){
							self.popup.css(popStyle);
							self.popupShadow.css(popShadowStyle);
		},5);
		setTimeout(function(){
			self.popup.fadeIn(self.options.delay,function(){
			self.popupShadow.fadeIn(self.options.delay,function(){
																	if(func && !self.isShow){
																		func.apply(this,args);
																	}
																	//存储当前弹出框的状态;
																	self.isShow = true;
																	//让隐藏的文本框获得焦点;
																	self.hiddenBtn.focus();
																 });																										
			});
		},6);
	},
	hide:function(){
		var self = this;
		var len = arguments.length;
		if(len >= 1){
			var args = Array.prototype.slice.call(arguments);
			var func = args.shift();
			if(!$.isFunction(func)){
				alert('请检查第一个参数是否为函数对象！');	
			};
		};
		this.popup.fadeOut(self.options.delay,function(){
				self.popupShadow.fadeOut(self.options.delay,function(){
						if(func){
							self.overlay.fadeOut(self.options.delay,function(){
													func.apply(this,args);
													//修正IE6弹出对话框不能关闭的bug;
													self.overlay.css("display",'none');
												});	
						}else{
							self.overlay.fadeOut(self.options.delay,function(){
													//修正IE6弹出对话框不能关闭的bug;
													self.overlay.css("display",'none');						 
													});
						};
						//修正IE6弹出对话框不能关闭的bug;
						self.popupShadow.css("display",'none');
				});
				//修正IE6弹出对话框不能关闭的bug;
				self.popup.css("display",'none');
		});
		//$('body').removeAttr('style');
		$(window).unbind('resize');
		$(window).unbind('scroll');
		$(this.overlay).unbind('click');
		$.Msg[$.Msg.NUM] = null;
		$.Msg.NUM = ($.Msg.NUM--) <= 0 ? 0 :$.Msg.NUM--; 
		this.isShow = false;
	},
	setPopup:function(obj){
		this.popup = obj;
	},
	getPopup:function(){
		return this.popup;
	},
	getShadow:function(){
		return 	$(this.popupShadow);
	},
	getShadowOffset:function(){
		return 	this.shadowOffset;
	},
	getStatus:function(){
		return 	this.isShow;
	},
	repaint:function(){
		var h = $(this.popup).outerHeight();
		$(this.popup).css({'margin-top': - h/2});
		$(this.popupShadow).css({'margin-top': - h/2 - this.shadowOffset,'height':h + (this.shadowOffset)*2});
		//将弹出层的高度存储下来方便动态改变其高度;
		$(this.popup).data('liveH',h);
	}
}
///
//用户按下Esc键关闭弹出层,按下Enter键触发提交事件;
$(document).bind("keydown",function(e){
	var key = e.keyCode;
	if($.Msg.NUM > 0 && (key == 27 || key == 13)){
			for(var i = $.Msg.NUM - 1; i>=0 ;i--){
				//console.log(i);
				if($.Msg[i].getStatus() && $.Msg[i].isEscAndEnter){
					if(key == 27){
						$.Msg[i].hide();
					}else if(key == 13){
						//所有btnSubmit都绑定了click事件，仅仅触发第一个btnSubmit按钮的click事件;
						$('.btnSubmit',$.Msg[i].popup).focus().trigger("click");
						//alert($.Msg[i].html());
					};
					break;
				};
			}
	}
});
//页面关闭后，删除已经存在的对象;
$(window).bind("unload",function(){
		$(document).unbind("keydown");
		for(var i = $.Msg.NUM - 1; i>=0 ;i--){
				if($.Msg[i]){
					delete $.Msg[i];	
				}
		};
		$.Msg.NUM = 0;
})
})(jQuery)
