(function($){
	$.popwindowclass = function (){};
	$.fn.keepvalue = function (){
		$.popwindow = $.popwindow || new $.popwindowclass();
		this.each(function(){
			this.id = this.id||'form_autoid_'+$.popwindow.checkform.length;
			$.popwindow.checkform.push('#'+this.id);
			var me = this;
			me.oldvalue = [];
			me.oldlength = 0;
			$(this).find('input[@type*=text],input[@type*=hidden],input[@type*=radio],input[@type*=checkbox],select,textarea').each(function(){
				if(typeof(this.name)!='undefined'&&this.name!=''&&((this.type!='checkbox'&&this.type!='radio')||this.checked)){
					me.oldvalue[this.name]=this.value;
					me.oldlength++;
				}
			});
		});
		if(this.length){
			$('a').each(function(){
				var href= $(this).attr('href');
				if(href&&href!='#'&&href!=''&&href.indexOf('void(0)')==-1){
					$(this).bind('click',function(){return $.popwindow.checkmodify(this);});
				}
			});
			$("form").not($.popwindow.checkform.join(',')).each(function(){
				var action= $(this).attr('action');
				if(action&&action!='#'&&action!=''&&action.indexOf('void(0)')==-1){
					$(this).bind('submit',function(){$.popwindow.checkmodify(this);return false;});
				}
			});
		}
	};
	$.fn.popwindow = function (){
		$.popwindow = $.popwindow || new $.popwindowclass();
		this.each(function(){
			$(this).bind('click',function(){return $.popwindow.facewindow(this);});
		});
	};
	$.fn.popreturn = function (){
		$.popwindow = $.popwindow || new $.popwindowclass();
		this.each(function(){
			var tp = $(this).attr('type');
			if(tp == 'submit'){
				$(this).bind('click',function(){
					$(this).parents('form').eq(0).ajaxSubmit(function(data){
						$.popwindow.returnshow(data);
					});
					return false;
				});
			}else{
				$(this).bind('click',function(){
					var href = $(this).attr('href')||$(this).attr('src')||false;
					if(href){
						$.get(href,function(data){
							$.popwindow.returnshow(data);
						});
					}
					return false;
				});
			}
		});
	};
	$.extend($.popwindowclass.prototype,{
		overlay:			true,
		checked:			false,
		opacity_overlay:	0.3,
		opacity_iframe:		0.5,
		title:				'没有保存的更改',
		systitle:			'系统提示',
		alerttitle:			'提示',
		syssuccess:			'<p>你的成功进行了该操作！</p>',
		syslost:			'<p>很遗憾,你的操作失败！</p>',
		body:				'<p>您的部分修改尚未保存。您想现在保存修改吗？</p>',
		button_ok:			{id:'popwin_btn_ok',text:'确认'},
		button_cancel:		{id:'popwin_btn_cancel',text:'取消'},
		button_save:		{id:'popwin_btn_save',text:'保存'},
		button_nosave:		{id:'popwin_btn_nosave',text:'不保存'},
		button_delete:		{id:'popwin_btn_delete',text:'删除'},
		button_close:		{id:'popwin_btn_close',text:'关闭'},
		button_submit:		{id:'popwin_btn_submit',text:'提交'},
		loadtext:			'加载中...',
		relchecktag:		'check',
		relpoptag:			'pop',
		relpopreturntag:	'return',
		width:				360,
		height:				260,
		baseurl:			'',
		content:			'',
		eventelement:		null,
		eventform:			null,
		result:				null,
		me:					{},
		checkform:			[],
		ie6:				false,
		files: {
			js: {popwindow:'jquery.popwindow.js'},
			css: {popwindow:'css/jquery.popwindow.css'},
			images: {
				blank:'images/blank.gif',
				loading:'images/loading.gif',
				success:'images/success.gif',
				lost:'images/lost.gif'
			}
		},
		keys: {close: 'c',prev: 'p',next:	'n'},
		domready: function(){
			var src = $('script[@src*='+this.files.js.popwindow+']').attr('src');
			this.baseurl = src.substring(0, src.indexOf(this.files.js.popwindow));	
			var me = this;
			$.each(this.files, function(group, val){
				$.each(this, function(file, val){
					me.files[group][file] = me.baseurl+val;
				});
			});
			$('head').append('<link rel="stylesheet" type="text/css" href="'+ this.files.css.popwindow +'" />');
			$('body').append('\
<iframe id="pop_iframe" src="javascript:false;" style="position:absolute;left:0;top:0;display:none;z-index:997;" frameborder="0" scrolling="no"></iframe>\
<div id="pop_dialog_bg" style="position:absolute;display:none;left:0;top:0;z-index:998;background:#666666;"></div>\
<div id="pop_body">\
<table id="pop_dialog_table" class="pop_dialog_table" style="position:absolute;left:0;top:0;z-index:999;display:none;">\
<tr>\
<td class="pop_topleft"></td>\
<td class="pop_border"></td>\
<td class="pop_topright"></td>\
</tr>\
<tr>\
<td class="pop_border"></td>\
<td class="pop_content" id="pop_content">\
</td>\
<td class="pop_border"></td>\
</tr>\
<tr><td class="pop_bottomleft"></td>\
<td class="pop_border"></td>\
<td class="pop_bottomright"></td>\
</tr>\
</table></div>');
			$('#pop_iframe').css('opacity',0);
			$('#pop_dialog_bg').css('opacity',this.opacity_overlay);
			$('.pop_topleft,.pop_border,.pop_topright,.pop_bottomleft,.pop_bottomright').css('opacity',this.opacity_iframe);
			$(window).resize(function(){ $.popwindow.resize(); });
			$('#pop_dialog_bg').unbind().click(function(){$.popwindow.finish();return false;});
			$('[@rel*='+this.relchecktag+']').keepvalue();
			$('[@rel*='+this.relpoptag+']').popwindow();
			$('[@rel*='+this.relpopreturntag+']').popreturn();
			this.ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !/MSIE 7.0/.test(navigator.userAgent);
			return true;
		},
		checkmodify: function(evenobj){
			if(this.checked) return true;
			var kept = true,par = this;
			$('[@rel*='+this.relchecktag+']').each(function(){
				var me = this;
				me.newvalue = [];
				me.newlength = 0;
				$(this).find('input[@type*=text],input[@type*=hidden],input[@type*=radio],input[@type*=checkbox],select,textarea').each(function(){
					if(typeof(this.name)!='undefined'&&this.name!=''&&((this.type!='checkbox'&&this.type!='radio')||this.checked)){
						me.newvalue[this.name]=this.value;
						me.newlength++;
					}
				});
				if(me.oldlength==me.newlength){
					for(i in me.oldvalue){
						if(me.oldvalue[i]!=me.newvalue[i]) kept=false;
					}
				}else{
					kept=false;
				}
				if(!kept) par.eventform = me;
			});
			if(!kept){
				this.eventelement = evenobj;
				$('#pop_content').html(this.counstructpop({buttons:['SAVE','NOSAVE','CANCEL']}));
				this.resize();
				if(this.overlay){
					$('#pop_dialog_bg').fadeIn();
				}
				$('#pop_iframe,#pop_dialog_table').show();
				
			}
			return kept;
		},
		facewindow: function(obj){
			var href = $(obj).attr('href')||$(obj).attr('src')||false;
			if(!href) return false;
			var showobj='';
			var len = $(obj).attr('len') || 'normal';
			switch(len){
				case 'short':
				$('#pop_body').addClass('small_pop');
				break;
				case 'long':
				$('#pop_body').addClass('long_pop');
				break;
			}
			if(href==''||href=='#'){
				$('#pop_content').html(this.counstructpop({title:$(obj).attr('title'),body:'',buttons:['OK','CLOSE']}));
				$('#dialog_body').empty().append($(obj).clone());
			}else if(href.indexOf('#')==0){
				var formchk = $(href+' form').length || [],html = $(href).html().replace(/_jq_popwindow/ig,'');
				$('#pop_content').html(this.counstructpop({title:$(obj).attr('title'),body:'',buttons:(formchk?['SUBMIT','CANCEL']:['OK'])}));
				$('#dialog_body').html(html);
				$('#dialog_body form').each(function(){
					if(this.getAttributeNode('action')){
						this.getAttributeNode('action').nodeValue = $(obj).attr('action');
					}else{
						this.setAttribute('action',$(obj).attr('action'));
					}
				});
				$(href).find('[id],[name]').each(function(){
					if(this.id&&this.id.indexOf('_jq_popwindow')==-1) this.id=this.id + '_jq_popwindow';
					if(this.name&&this.name.indexOf('_jq_popwindow')==-1){
						if(this.outerHTML){
							$(this).attr('name_jq_attr',this.name + '_jq_popwindow');
							$(this).removeAttr('name');
							this.outerHTML = this.outerHTML.replace(/_jq_attr/ig,'');
						}else{
							this.name=this.name + '_jq_popwindow';
						}
					}
				});
			}else{
				this.loading();
				$.get(href,function(data){
					var re = $.popwindow.gettitle(data);
					title =re.title;
					data =re.data;
					if($(data).find('form').length){
						$('#pop_content').html($.popwindow.counstructpop({title:title,body:data,buttons:['SUBMIT','CANCEL']}));
					}else{
						$('#pop_content').html($.popwindow.counstructpop({title:title,body:data,buttons:['OK','CLOSE']}));
					}
				});
			}
			this.resize();
			if(this.overlay){
				$('#pop_dialog_bg').fadeIn();
			}
			$('#pop_iframe,#pop_dialog_table').show();			
			
			return false;
		},
		confirm: function(title,msg,okcallback,cancelcallback){
			$('#pop_content').html(this.counstructpop({title:title,body:'<p>'+msg+'</p>',buttons:['OK','CANCEL']}));
			if(okcallback){
				$('#pop_content').find('#popwin_btn_ok').unbind('click').bind('click',okcallback);
			}
			if(cancelcallback){
				$('#pop_content').find('#popwin_btn_ok').unbind('click').bind('click',cancelcallback);
			}
			this.resize();
			if(this.overlay){
				$('#pop_dialog_bg').fadeIn();
			}
			$('#pop_iframe,#pop_dialog_table').show();
		},
		alert: function(msg){
			$('#pop_body').addClass('small_pop');
			$('#pop_content').html(this.counstructpop({title:this.alerttitle,body:'<p>'+msg+'</p>',buttons:['OK']}));
			this.resize();
			if(this.overlay){
				$('#pop_dialog_bg').fadeIn();
			}
			$('#pop_iframe,#pop_dialog_table').show();
		},
		returnshow: function(data){
			if(this != $.popwindow){
				me = $.popwindow;
			}else{
				me = this;
			}
			if(me.empty(data) == true){
				$('#pop_body').addClass('small_pop');
				$('#pop_content').html(me.counstructpop({title:me.systitle,body:me.syslost,buttons:['OK']}));
				$('#dialog_body').addClass('retrunlost');
			}else if(me.empty(data) == false){
				$('#pop_body').addClass('small_pop');
				$('#pop_content').html(me.counstructpop({title:me.systitle,body:me.syssuccess,buttons:['OK']}));
				$('#dialog_body').addClass('retrunsuccess');
			}else{
				var re = $.popwindow.gettitle(data);
				title =re.title;
				data =re.data;
				if($(data).find('form').length){
					$('#pop_content').html(me.counstructpop({title:title,body:data,buttons:['SUBMIT','CANCEL']}));
				}else{
					$('#pop_content').html(me.counstructpop({title:title,body:data,buttons:['OK']}));
				}
			}
			me.resize();
			if(me.overlay){
				$('#pop_dialog_bg').fadeIn();
			}
			$('#pop_iframe,#pop_dialog_table').show();
		},
		gourl: function(){
			if(this.eventelement){
				this.checked = true;
				if(this.eventelement.href) location.href=this.eventelement.href;
				else if(this.eventelement.action) this.submit();
			}
		},
		gosubmit: function(){
			if(this.eventform){
				$(this.eventform).submit();
			}
		},
		gettitle: function(data){
			var re,_b;
			data = data.replace('\r','\n');
			re = new RegExp("<title(?:.*)>((?:.|\n)*)<\/title>","gi");
			_b = re.exec(data);
			return {title:(_b!=null?RegExp.$1:''),data:(_b!=null ? data.replace(re,''):data)};
		},
		loading: function(){
			$('#pop_content').html('<h2 class="dialog_loading">'+this.loadtext+'</h2>');
		},
		resize: function(options){
			options = $.extend({}, options);
			var pagescroll = this.getpagescroll();
			var nwidth = options.nwidth || parseInt($('#pop_dialog_table').width(),10) || this.width;
			var nheight = options.nheight || parseInt($('#pop_dialog_table').height(),10) || this.height;
			var pagepos = this.getposition(nwidth,nheight);
			var css = {left: pagescroll.xscroll+pagepos.l,top:pagescroll.yscroll+pagepos.t};
			$('#pop_dialog_table').css(css);
			var brwidth = $(document).width();
			var brheight = $(document).height();
			if(this.ie6){
				brwidth -= 21;
				brheight -= 4;
			}
			if(this.overlay){
				$('#pop_dialog_bg').css({width:brwidth,height:brheight});
				$('#pop_iframe').css({width:brwidth,height:brheight,left:0,top:0});
			}else{
				$('#pop_iframe').css({width:$('#pop_dialog_table').width(),height:$('#pop_dialog_table').height(),left:css.left,top:css.top});
			}
			return true;
		},
		finish: function(){
			$('#pop_iframe,#pop_dialog_table').hide();
			if(this.overlay){
				$('#pop_dialog_bg').fadeOut();
			}
			$('#pop_body').removeClass('small_pop long_pop');
			$('#dialog_body').removeClass('success lost');
			this.eventelement = null;
			this.eventform = null;
			this.checked = false;
			$.popwindow.keyboardnav_disable();
		},
		getposition: function(w,h){
			var myWidth = 0, myHeight = 0;
			if(typeof(window.innerWidth)=="number"){
				myWidth = window.innerWidth;
				myHeight = window.innerHeight;
			}else{
				if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
					myWidth = document.documentElement.clientWidth;
					myHeight = document.documentElement.clientHeight;
				}else{
					if(document.body && (document.body.clientWidth || document.body.clientHeight)){
						myWidth = document.body.clientWidth;
						myHeight = document.body.clientHeight;
					}
				}
			}
			var l = myWidth - w,t = myHeight - h;
			l = l<=0 ? 0 : l/2;
			t = t<=0 ? 0 : t/3;
			return {l:parseInt(l),t:parseInt(t)};
		},
		getpagescroll: function(){
			var xscroll, yscroll;
			if (self.pageYOffset){
				yscroll = self.pageYOffset;
				xscroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop){
				yscroll = document.documentElement.scrollTop;
				xscroll = document.documentElement.scrollLeft;
			} else if (document.body){
				yscroll = document.body.scrollTop;
				xscroll = document.body.scrollLeft;	
			}
			var arraypagescroll = {'xscroll':xscroll,'yscroll':yscroll};
			return arraypagescroll;
		},
		keyboardnav_enable: function(){
			$(document).keydown(function(objEvent) {$.popwindow.keyboardnav_action(objEvent);});
		},
		keyboardnav_disable: function(){
			$(document).unbind();
		},
		keyboardnav_action: function(objEvent){
			objEvent = objEvent || window.event;
			var keycode = objEvent.keyCode;
			var escapeKey = objEvent.DOM_VK_ESCAPE /* moz */ || 27;
			var key = String.fromCharCode(keycode).toLowerCase();
			if ( key === this.keys.close || keycode === escapeKey ){return $.popwindow.finish();}
			return true;
		},
		empty: function(a){
			if(!a||a=='0'||a=='false'||a==[]){
				return true;
			}else if(a==1||a=='1'||a==true||a=='true'){
				return false;
			}else{
				return 'no check';
			}
		},
		counstructpop: function(options){
			options = $.extend({}, options);
			var html = [];
			if(options.title!=''){
				html.push('<h2><span>'+(options.title||this.title)+'</span></h2>');
			}
			html.push('<div class="dialog_content">');
			if(options.summary){
				html.push('<div class="dialog_summary">'+options.summary+'</div>');
			}
			html.push('<div class="dialog_body" id="dialog_body">'+(options.body||this.body)+'</div>');
			options.buttons = options.buttons||['OK','CANCEL'];
			html.push('<div class="dialog_buttons">');
			if(options.buttons_msg){
				html.push('<div class="dialog_buttons_msg">'+options.buttons_msg+'</div>');
			}
			if(typeof(options.buttons)!='array'&&typeof(options.buttons)!='object'){
				options.buttons = [options.buttons];
			}
			var buttonhtml;
			for(i in options.buttons){
				buttonhtml = this.buttons(options.buttons[i]);
				if(buttonhtml) html.push(buttonhtml);
			}
			html.push('</div>');
			html.push('</div>');
			return html.join('');
		},
		buttons: function(type){
			switch(type){
				case 'OK':
				return '<input id="'+this.button_ok.id+'" class="inputbutton ok" type="button" value="'+this.button_ok.text+'" onclick="$.popwindow.finish();" />';
				case 'CANCEL':
				return '<input id="'+this.button_cancel.id+'" class="inputbutton cancel" type="button" value="'+this.button_cancel.text+'" onclick="$.popwindow.finish();" />';
				case 'SAVE':
				return '<input id="'+this.button_save.id+'" class="inputbutton ok" type="button" value="'+this.button_save.text+'" onclick="$.popwindow.gosubmit();" />';
				case 'NOSAVE':
				return '<input id="'+this.button_nosave.id+'" class="inputbutton cancel" type="button" value="'+this.button_nosave.text+'" onclick="$.popwindow.gourl();" />';
				case 'DELETE':
				return '<input id="'+this.button_delete.id+'" class="inputbutton ok" type="button" value="'+this.button_delete.text+'" onclick="$.popwindow.finish();" />';
				case 'CLOSE':
				return '<input id="'+this.button_close.id+'" class="inputbutton ok" type="button" value="'+this.button_close.text+'" onclick="$.popwindow.finish();" />';
				case 'SUBMIT':
				return '<input id="'+this.button_submit.id+'" class="inputbutton ok" type="button" value="'+this.button_submit.text+'" onclick="$(\'<input type=\\\'submit\\\' style=\\\'display:none;\\\' />\').appendTo($(\'#pop_content form\')).click().remove();" />';
				default :
				return false;
			}
		}
	});
	$(function(){
		$.popwindow = $.popwindow || new $.popwindowclass();
		$.popwindow.domready();
	});
})(jQuery);
