/*------------jqpanel--------------*/
/*
@author lwg<lwg_8088@yahoo.com.cn>
@update 2009-07-06
*/

/*------------global------------*/
(function() {
	var ua = navigator.userAgent;
	isWebKit = /WebKit/.test(ua);
	isOldWebKit = isWebKit && !window.getSelection().getRangeAt;
	isIE6 = $.browser.msie && /MSIE [56]/.test(ua);
	isGecko = !isWebKit && /Gecko/.test(ua);
	isMac = ua.indexOf('Mac') != -1;
	isChrome = /Chrome/.test(ua);

	$.browser.webkit = isWebKit;
	$.browser.oldwebkit = isOldWebKit;
	$.browser.ie6 = isIE6;
	$.browser.gecko = isGecko;
	$.browser.mac = isMac;

	$.Dom = {
        getViewPort: function() {
			var d = document, b = d.body;
            var mode = d.compatMode;

            var width = self.innerWidth;  // Safari
            var height = self.innerHeight; // Safari, Opera
			if (mode || $.browser.msie) { // IE, Gecko, Opera
                width = (mode == 'CSS1Compat') ? d.documentElement.clientWidth : b.clientWidth;
				if (!$.browser.opera ) height = (mode == 'CSS1Compat') ? d.documentElement.clientHeight : b.clientHeight;
            }

			return {
				x: Math.max(d.documentElement.scrollLeft, b.scrollLeft),
				y: Math.max(d.documentElement.scrollTop, b.scrollTop),
				w: width,
				h: height
			};
        },

		getContextXY : function (src_id, dst_id, place, pageXY){
			var opt = {}, dst_pos, src_pos, obj_src, obj_dst, vp;

			obj_src = $(src_id);
			if (obj_src.length == 0) return opt;
			src_pos = { x:obj_src.offset().left, y:obj_src.offset().top, w:obj_src.width(), h:obj_src.height() };

			if (dst_id && (obj_dst = $(dst_id)).length > 0) dst_pos = { x:obj_dst.offset().left, y:obj_dst.offset().top, w:obj_dst.width(), h:obj_dst.innerHeight() };
			else if (pageXY && pageXY.x && pageXY.y) dst_pos = { x:pageXY.x, y:pageXY.y, w:0, h:0 };
			else return opt;

			vp = this.getViewPort();

			if (!place) place = "bottom";
			if (place == "bottom"){
				opt.x = dst_pos.x;
				if (src_pos.h+dst_pos.y+dst_pos.h > vp.y+vp.h && dst_pos.y-vp.y > src_pos.h) opt.y = dst_pos.y - src_pos.h;
				else opt.y = dst_pos.y + dst_pos.h;
			}
			else if (place == "right"){
				if (dst_pos.x+dst_pos.w+src_pos.w > vp.x+vp.w && dst_pos.x-vp.x>src_pos.w)opt.x = dst_pos.x-src_pos.w;
				else opt.x = dst_pos.x+dst_pos.w;
				opt.y = dst_pos.y;
			}
			else if (place == "left"){
				if (dst_pos.x-src_pos.w < vp.x && dst_pos.x-vp.x<src_pos.w)opt.x = dst_pos.x+dst_pos.w;
				else opt.x = dst_pos.x-src_pos.w;
				opt.y = dst_pos.y;
			}
			else if (place == "top"){
				opt.x = dst_pos.x;
				if (dst_pos.y-vp.y < src_pos.h && vp.h+vp.y-dst_pos.y-dst_pos.h > src_pos.h) opt.y = dst_pos.y + dst_pos.h;
				else opt.y = dst_pos.y-src_pos.h;
			}

			if (place == "bottom" || place == "top"){
				if (dst_pos.x+src_pos.w > vp.x+vp.w && dst_pos.x+dst_pos.w-vp.x>src_pos.w)opt.x = dst_pos.x+dst_pos.w-src_pos.w;
			}
			if (place == "left" || place == "right"){
				if (src_pos.h+dst_pos.y > vp.y+vp.h && dst_pos.y+dst_pos.h-vp.y > src_pos.h) opt.y = dst_pos.y+dst_pos.h - src_pos.h;
			}
			return opt;
		},

		getIframeWindow : function(id) {
			var el = (typeof id == 'object') ? $(id) : $("#"+id);
			return el.contentWindow;
		},

		getIframeDocument : function(id) {
			var el = (typeof id == 'object') ? $(id) : $("#"+id);
			return el.contentDocument||el.contentWindow.document;
		}
	};

	$.global = {
		counter_id : 0,
		generateId : function (el, prefix) {
			if (el && el.id) return el.id;
			var id = (prefix || 'jqauto_') + $.global.counter_id++;
			if (el) el.id = id;
			return id;
		},

		htmlEncode : function (s) {
			return s ? ('' + s).replace(/[<>&\"]/g, function (c, b) {
				switch (c) {
					case '&': return '&amp;';
					case '"': return '&quot;';
					case '<': return '&lt;';
					case '>': return '&gt;';
				}
				return c;
			}) : s;
		}
	};

	/*---------jqDnR-----------*/
	$.fn.jqDrag=function (handle, proxy, cb){
		return eachJqDnR(this,handle,'drag', proxy, cb);
	};

	$.fn.jqResize=function (handle, proxy, cb){
		return eachJqDnR(this,handle,'resize', proxy, cb);
	};

	var dnr={}, E, use_proxy, obj_proxy, stop_cb, pos={};

	$.jqDnR={
		drag:function (ev){
			if (use_proxy && !obj_proxy){
				$(document.body).append('<div id="jqDnR_move" style="position:absolute; border:1px dotted #000; background:#ccc; opacity:0.5; filter:alpha(opacity=50)"></div>');
				obj_proxy = $("#jqDnR_move");
				try{
					obj_proxy.css({left:dnr.X, top:dnr.Y, width:dnr.W, height:dnr.H, marginLeft:dnr.marginLeft, marginTop:dnr.marginTop, zIndex:(dnr.zIndex+1)});
				} catch(e){}
			}

			var sl = $(document).scrollLeft(), st = $(document).scrollTop();

			if (dnr.kind == 'drag') {
				var left = Math.max(5-dnr.marginLeft+sl, dnr.X+ev.pageX-dnr.pX);
				var top = Math.max(5-dnr.marginTop+st, dnr.Y+ev.pageY-dnr.pY);
				left = Math.min(left, dnr.vp.w-dnr.W-dnr.marginLeft-5+sl);
				top = Math.min(top, dnr.vp.h-dnr.H-dnr.marginTop-5+st);
				pos = {left:left, top:top};
			}
			else {
				var width = Math.max(ev.pageX-dnr.pX+dnr.W, 0);
				var height = Math.max(ev.pageY-dnr.pY+dnr.H, 0);
				width = Math.min(width, dnr.vp.w+sl-dnr.marginLeft-dnr.X-5);
				height = Math.min(height, dnr.vp.h+st-dnr.marginTop-dnr.Y-5);
				pos = {width:width, height:height};
			}

			if (obj_proxy)obj_proxy.css(pos);
			else E.css(pos);
			return false;
		},

		stop:function (ev){
			if (obj_proxy) obj_proxy.remove();

			if (stop_cb)stop_cb(pos);
			else E.css(pos);

			pos = {};
			dnr={};
			E = null;
			use_proxy = false;
			obj_proxy = null;
			stop_cb = null;
			$().unbind('mousemove',$.jqDnR.drag).unbind('mouseup',$.jqDnR.stop);
		}
	};

	function eachJqDnR(obj, handle, kind, proxy, cb){
		return obj.each(function (){
			handle=(handle)?$(handle,obj):obj;
			handle.bind('mousedown',{obj:obj,kind:kind,proxy:proxy,cb:cb},function (ev){
				var d=ev.data,p={};
				stop_cb = cb;

				E=d.obj;
				if(E.css('position')!='relative'){
					try{
						p = E.position();
					}catch(e){}
				}

				dnr={
					X:p.left||getCss('left', 0),
					Y:p.top||getCss('top', 0),
					//W:getCss('width')||E[0].scrollWidth||0,
					//H:getCss('height')||E[0].scrollHeight||0,
					W:E.width(),
					H:E.height(),
					pX:ev.pageX,
					pY:ev.pageY,
					kind:d.kind,
					marginLeft:getCss('margin-left', 0),
					marginTop:getCss('margin-top', 0),
					zIndex:getCss('z-index', 0),
					vp:$.Dom.getViewPort()
				};

				use_proxy = d.proxy;

				$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
				return false;
			});
		});
	}

	getCss=function (kind, defaultVal){
		return parseInt(E.css(kind))||defaultVal;
	};

	/*-------panel-----------*/
	$.JqPanel = {
		panels : [],
		currId : 0,
		groupAreas : [],
		groupModules : [],
		zIndex : 300000,

		getJqObj : function(el)
		{
			return (typeof el == 'object') ? $(el) : $("#"+el);
		},

		getPanel : function(id)
		{
			var ix = 0, p, v, i;
			if (id) {
				if (typeof id == 'object' && id.id && this.panels[id.id]){
					return this.panels[id.id];
				}
				else if (typeof id == 'string' && this.panels[id]){
					return this.panels[id];
				}
				return null;
			}
			for (i in this.panels){
				if ((v = this.panels[i]) && (v.type == 'panel' || v.type == 'alert' || v.type == 'confirm') && v.zIndex > ix && v.isHide === false){
					p = v;
					ix = v.zIndex;
				}
			}
			return p;
		},

		alert : function(txt, callback)
		{
			return new PanelElement({
				title : "信息提示",
				type : 'alert',
				mask : true,
				callback : callback,
				content : $.global.htmlEncode(txt),
				width : 400,
				id : $.global.generateId()
			}).show();
		},

		confirm : function(txt, callback)
		{
			return new PanelElement({
				title : "信息提示",
				type : 'confirm',
				mask : true,
				callback : callback,
				content : $.global.htmlEncode(txt),
				width : 400,
				id : $.global.generateId()
			}).show();
		},

		panel : function(opt)
		{
			if (!opt.id) opt.id = $.global.generateId();
			return new PanelElement(opt).show();
		},

		dropdown : function(el, opt, ifDropDownHandler)
		{
			el = this.getJqObj(el);
			if (!el) return false;

			var p, on_panel=false, on_el=false, tmo_el = null, tmo_panel = null;

			opt = opt || {};
			opt.type = 'dropdown';
			if (!opt.resizeable)opt.resizeable = false;
			if (!opt.moveable)opt.moveable = false;
			if (!opt.closeable)opt.closeable = false;
			if (!opt.minimizable)opt.minimizable = false;			
			if (!opt.context)opt.context = [el, opt.align || 'bottom'];
			if (!opt.id) opt.id = $.global.generateId();

			function clearTimer()
			{
				if(tmo_el){
					clearTimeout(tmo_el);
					tmo_el=null;
				}
				if(tmo_panel){
					clearTimeout(tmo_panel);
					tmo_panel=null;
				}
			}

			var over_handler = function(e){
				if (typeof ifDropDownHandler == 'function' && !ifDropDownHandler()){
					return false;
				}

				if(!p){
					p = new PanelElement(opt);
					p.jqp_panel.hover(
						function(){
							p.show();
							on_panel = true;
							clearTimer();
						},
						function(){
							on_panel = false;
							tmo_panel = setTimeout(function (){
								if (!on_el)p.close();
								if(p.overClassName)el.removeClass(p.overClassName);
							}, 100);
						}
					);
				}
				p.show().setPlace();
				if(p.overClassName)el.addClass(p.overClassName);
				on_el = true;
				clearTimer();
			}

			var out_handler = function(){
				if (typeof ifDropDownHandler == 'function' && !ifDropDownHandler()){
					return false;
				}
				if(!p)return false;
				on_el = false;
				tmo_el = setTimeout(function (){
					if (!on_panel)p.close();
					if(p.overClassName)el.removeClass(p.overClassName);
				},100);
			}

			if (opt.mouseType == 'click'){
				el.click(function (e){ over_handler(e); return false; });
				el.mouseout(out_handler);
			}
			else el.hover(over_handler, out_handler);
		},

		context : function(el, opt, ifContextHandler)
		{
			el = this.getJqObj(el);
			if (!el) return false;

			var p, on_panel=false, on_el=false, tmo_el = null, tmo_panel = null;

			opt = $.extend(opt || {}, {
				type:'context',
				resizeable:false,
				moveable:false,
				closeable:false,
				minimizable:false
			});
			opt.context = [];
			if (!opt.id) opt.id = $.global.generateId();

			var closePanel = function(){
				if (p) p.close();
				$(document).unbind('mousedown', closePanel);
			}

			el.bind('contextmenu', function(e){
				if (typeof ifContextHandler == 'function' && !ifContextHandler()){
					return false;
				}

				if(!p) p = new PanelElement(opt);
				p.left = e.pageX+10;
				p.top = e.pageY;
				p.setPlace().show();

				$(document).bind('mousedown', closePanel);
				return false;
			});

			el.bind('mousedown', function(e){return false;});
		},

		module : function (opt)
		{
			var p, id;

			opt = opt || {};

			if (!opt.id || $('#'+opt.id).size() == 0){
				alert('请用文档对象id作为面板id');
			}

			opt.inline = true;
			opt.type = 'module';

			p = new PanelElement(opt);

			if (p.visibility == 'visible'){
				p.show();
			}
			else if (p.visibility == 'minsize'){
				p.showMinimiz();
			}

			return p;
		},

		moduleGroup : function(el, panels)
		{
			el = this.getJqObj(el);
			if (!el) return false;

			$(el).each(function(i) { $.JqPanel.groupAreas[i] = $(this); });
			$.each(panels, function(key, val){
				if (val.id) $.JqPanel.groupModules[val.id] = val;
				else if (typeof val == 'object' || typeof val == 'array'){
					$.each(val, function(k, v){
						if (v.id)$.JqPanel.groupModules[v.id] = v;
					});
				}
			});
		},

		closePanel : function (id)
		{ 
			var panel = this.getPanel(id); 
			if(panel)panel.close(); 
		}
	};


	function PanelElement(opt)
	{
		opt = opt || {};

		this.id = opt.id || $.global.generateId();

		if ($.JqPanel.panels[this.id]){
			return $.JqPanel.panels[this.id];
		}
		else {
			$.JqPanel.panels[this.id] = this;
		}

		this.type = opt.type || 'panel';
		this.content = opt.content || '';
		this.title = opt.title || '';
		this.url = opt.url && opt.url != '#' ? opt.url : '';
		this.inline = opt.inline || false;
		this.width = this.inline ? "100%" : (opt.width || 0);
		this.height = parseInt(opt.height || 0);
		this.left = parseInt(opt.left || 0);
		this.top = parseInt(opt.top || 0);
		this.minWidth = 100;
		this.minHeight = (this.type == 'dropdown' || this.type == 'context') ? 20 : 70;
		this.mask = (opt.mask || this.type == 'alert' || this.type == 'confirm') ? true : false;
		this.moveable = opt.moveable != false ? true : false;
		this.resizeable = opt.resizeable != false ? true : false;
		this.closeable = opt.closeable != false ? true : false;
		this.minimizable = opt.minimizable != false ? true : false;
		this.shadow = opt.shadow != false ? true : false;
		this.iframeScrolling = opt.iframeScrolling != 'no' ? 'yes' : 'no';
		this.refresh = opt.refresh || 0;
		this.el = opt.el || null;
		this.iframe = opt.iframe ? true : false;
		this.callback = opt.callback || null;
		this.visibility = opt.visibility || 'visible'; //visible、minsize、hidden
		this.opennew = opt.opennew ? true : false;
		this.context = opt.context || [];
		this.custom_vars = opt.custom_vars || [];
		this.className = opt.className || '';
		this.overClassName = opt.overClassName || '';
		this.closeText = opt.closeText || '';
		//this.align = 'center';

		this.tmpWidth = null;
		this.tmpHeight = null;
		this.isImage = false;
		this.jqp_panel = null;
		this.jqp_underlay = null;
		this.jqp_wrapper = null;
		this.jqp_iframe = null;
		this.jqp_canvas = null;
		this.jqpTmpCanvas = null;
		this.jqp_bd = null;
		this.jqp_ft = null;
		this.jqp_mask = null;
		this.jqp_minimiz = null;
		this.jqp_resize = null;
		this.jqp_refresh = null;
		this.jqp_load = null;
		this.zIndex = 0;
		this.hd_height= 0;
		this.ft_height= 0;
		this.isHide = null;
		this.isMin= false;
		this.loaded = false;
		this.error = '';

		var t = this, id, cls = '', dw = 0, dh = 0, vp, po, mdf, we, w, h_set=false, jqp_id, qm;
		var tmp_hd, tmp_bd;
		var showhd = showft = showbutton = showcancel = showicon = showrefresh = false;

		jqp_id = $("#"+t.id);
		if (jqp_id.size() > 0) {
			if ((tmp_hd = $(".hd", jqp_id)).size() > 0) t.title = tmp_hd.get(0);
			if ((tmp_bd = $(".bd", jqp_id)).size() > 0) t.content = tmp_bd.get(0);
		}
		if (t.content){
			if (typeof t.content == 'object'){
				id = $(t.content).attr('id');
				if (id) t.id = id;
				$(t.content).addClass("bd");
			}
		}

		if(t.content) t.setContent(t.content);
		else if (t.url) t.setUrl(t.url);

		cls += ' jqp_panel_' + t.type;
		if (t.inline)cls += ' jqp_inline';
		if (t.type == 'alert' || t.type == 'confirm'){
			t.resizeable = false;
			t.minimizable = false;
		}
		if (t.moveable)cls += ' jqp_hd_move';
		if (t.className)cls += ' '+t.className;

		if (t.type == 'alert' || t.type == 'confirm') {
			showbutton = true;
			showicon = true;
			this.height = '';
			if (t.type == 'confirm') showcancel = true;
		}
		if (t.type != 'alert' && t.type != 'confirm' && t.url) {
			if (t.refresh === true)showrefresh = true;
		}
		if (t.title || t.closeable || t.moveable || t.minimizable) showhd = true;
		if (showbutton || t.resizeable) showft = true;

		var str = '';
		if (t.mask){
			str += '<div id="'+t.id+'_mask" class="jqp_mask"></div>';
		}
		str += '	<div id="'+t.id+'_panel" class="jqp_panel '+cls+'">';
		if (t.shadow && !t.inline){
			str += '		<div class="jqp_underlay"></div>';
		}
		str += '			<div id="'+t.id+'" class="jqp_wrapper">';
		if (showhd) {
			str += '			<div class="hd">窗口</div>';
		}
		str += '				<div class="jqp_canvas"></div>';
		if (showft){
			str += '			<div class="ft"> ';
			if (showbutton) {
				str += '			<div class="jqp_button_group">';
				str += '				<button type="button" class="jqp_submit">确定</button>';
				if (showcancel){
					str += '			<button type="button" class="jqp_cancel">取消</button>';
				}
				str += '			</div>';
			}
			if (t.resizeable) {
				str += '			<div class="jqp_resize_br"></div>';
			}
			str +='				</div>';
		}
		str +='					<div class="jqp_ctrl_group_right">';
		if (t.closeable){
			str += '				<div class="jqp_close">'+(this.closeText?this.closeText:'&nbsp;')+'</div>';
		}
		if (t.minimizable){
			str += '				<div class="jqp_minimiz_open">&nbsp;</div>';
		}
		if (showrefresh){
			str += '				<div class="jqp_refresh">&nbsp;</div>';
		}
		str +='					</div>';
		if (showicon){
			str += '			<div class="jqp_icon"></div>';
		}
		str += '			</div>';
		str += '	</div>';		

		if (t.inline) {
			jqp_id.after(str);
			jqp_id.remove();
		}
		else {
			$("body").append(str);
			if (jqp_id && jqp_id.length > 0){
				jqp_id.remove();
			}
		}

		t.jqp_panel = $("#"+t.id+"_panel");
		t.jqp_wrapper = $(".jqp_wrapper", t.jqp_panel);
		if (t.mask){
			t.jqp_mask = $("#"+t.id + '_mask');
		}
		if (t.shadow && !t.inline){
			t.jqp_underlay = $(".jqp_underlay", t.jqp_panel);
		}		
		t.jqp_canvas = $(".jqp_canvas", t.jqp_panel);
		if (t.minimizable) t.jqp_minimiz = $(".jqp_minimiz_open", t.jqp_panel);
		if (t.resizeable) t.jqp_resize = $(".jqp_resize_br", t.jqp_panel);
		if (showrefresh) t.jqp_refresh = $('.jqp_refresh', t.jqp_panel);

		$('.jqp_ctrl_group_right', t.jqp_wrapper).css('width', $('.jqp_close', t.jqp_wrapper).outerWidth(true)+$('.jqp_minimiz_open', t.jqp_wrapper).outerWidth(true)+$('.jqp_refresh', t.jqp_wrapper).outerWidth(true));

		if (showhd){
			t.jqp_hd = $('.hd', t.jqp_panel);
			t.hd_height = t.jqp_hd.height();
			t.setTitle(t.title);
		}
		if (showft){
			t.jqp_ft = $('.ft', t.jqp_panel);
			t.ft_height = t.jqp_ft.outerHeight(true);
		}

		if (t.jqp_hd && t.moveable) t.jqp_panel.jqDrag(t.jqp_hd, true, function(pos){ t.moveBy(pos.left, pos.top);t.focus();});
		if (t.jqp_resize) t.jqp_panel.jqResize(t.jqp_resize, true, function(pos){ t.resize(pos.width, pos.height);t.focus();});

		t.jqp_panel.mousedown(function(e) {
			t.focus();
		});

		t.jqp_panel.click(function(e) {
			var className = e.target.className;
			switch (className) {
				case 'jqp_close':
					t.close();
					break;
				case 'jqp_refresh':
					t.doRefresh();
					break;
				case 'jqp_submit':
				case 'jqp_cancel':
					var cb = t.callback;
					if (t.callback)t.callback.call(t, className == 'jqp_submit' ? true : false);
					t.close();
					break;
				case 'jqp_minimiz_open':
				case 'jqp_minimiz_close':
					t.minimiz();
					break;
			}
			return true;
		});

		//$(window).bind('resize', function(){
			//t.resizeMask().setPlace();
		//});
	};

	PanelElement.prototype.showMask = function()
	{
		if (this.jqp_mask) {
			if (typeof document.body.style.maxHeight === "undefined") {
				//$("body","html").css({height: "100%", width:"100%"});
			}

			this.jqp_mask.css({left:$(document).scrollLeft(), top:$(document).scrollTop(), width:3000, height:$(document).height()+500});
			$(document.body).addClass("masked");
			$('body').css({overflow:'hidden'});
			if (!isGecko){
				$('html').css({overflow:'hidden'});
			}
			this.jqp_mask.show();
		}
		return this;
	};

	PanelElement.prototype.hideMask = function()
	{
		if (this.jqp_mask) {
			this.jqp_mask.hide();

			if (typeof document.body.style.maxHeight === "undefined") {
				//$("body","html").css({height: "auto", width:"auto"});
			}

			$(document.body).removeClass("masked");
			if (!isGecko){
				$('html').css({overflow:''});
			}
			$('body').css({overflow:''});
		}
		return this;
	};

	PanelElement.prototype.setScroll = function(bool)
	{
		if (isChrome || !this.jqp_iframe) return false;
		if (bool) {
			this.jqp_iframe.attr("scrolling", "yes");
			this.jqp_iframe.contents().find("body").attr("scroll", "yes");
		}
		else {
			this.jqp_iframe.attr("scrolling", "no");
			this.jqp_iframe.contents().find("body").attr("scroll", "no");
		}
	};

	PanelElement.prototype.setTitle = function(title)
	{
		var t = this;
		title = title || t.title;
		if (typeof title == 'object') {
			t.jqp_hd.replaceWith(title);
			t.jqp_hd = $(title);
		}
		else if(typeof title == 'string' && title != '') {
			t.jqp_hd.html(title);
		}
		return this;
	};

	PanelElement.prototype.setUrl = function(url)
	{
		if (url) {
			var baseURL, qm;
			this.isImage = false;
			this.url = url;
			this.content = null;
			this.loaded = false;

			if((qm = this.url.indexOf("?")) !== -1) baseURL = this.url.substr(0, qm);
			else baseURL = this.url;
			if(/\.(jpg|jpeg|png|gif|bmp)$/i.test(baseURL)){
				this.content = '<img src="'+this.url+'" onload="$.JqPanel.getPanel(\''+this.id+'\').hideLoading().replaceCanvas()">';
				this.url = '';
				this.isImage = true;
			}

			if (this.isHide === false) this.loadContent();	
		}
		return this;
	};

	PanelElement.prototype.setContent = function(content)
	{
		if (content) {
			this.isImage = false;
			this.content = content;
			this.loaded = false;
			this.url = '';
			if (this.isHide === false) this.loadContent();
		}
		return this;
	};

	PanelElement.prototype.loadContent = function()
	{
		var t = this, canvas;

		if (t.loaded) return this;
		t.loaded = true;

		if ((t.url == '' || t.url == '#') && t.content == '') {
			t.error = '未指定要显示内容或Url。';
			alert(t.error);
			return this;
		}
		t.error = '';

		t.showLoading();
		
		if (t.jqp_iframe){
			t.jqp_iframe.unbind();
			t.jqp_iframe.attr("src", "javascript:false");
			t.jqp_iframe.remove();
			delete t.jqp_iframe;
		}
		else if (t.jqp_bd){
			t.jqp_bd.remove();
			delete t.jqp_bd;
		}

		if (t.url && t.iframe){
			if (!t.width) t.width = 320;
			if (!t.height) t.height = 240;
			t.jqp_canvas.html('<iframe id="'+t.id+'_ifr" name="'+t.id+'_ifr" frameBorder="0" style="border:0px;width:100%;height:100%;overflow-x:hidden;"></iframe>');
			t.jqp_iframe = $("#"+t.id+ '_ifr');
			t.jqp_iframe.attr("src",t.getUrl());
			t.jqp_iframe.load(function(){
				t.hideLoading();
				if (t.type != 'alert' && t.type != 'confirm' && t.callback)t.callback.call(t, 'load');
				try{
					t.jqp_iframe.contents().find("head").append('<style type="text/css">html{overflow-x:hidden;overflow-y:auto;}*html body{min-width:auto;max-width:auto;width:auto;position:absolute;}</style>');
					var ifrDoc = t.jqp_iframe.get(0).contentDocument||t.jqp_iframe.get(0).contentWindow.document;
					$(ifrDoc).mousedown(function() { t.focus(); });
					var ifrWin = t.jqp_iframe.get(0).contentWindow;
					if (typeof ifrWin.onload == "function") {
						t.jqp_iframe.data("onload", ifrWin.onload);
					}
				}
				catch(e){}
			});
		}
		else {
			t.jqpTmpCanvas = $('<div class="jqp_canvas"></div>');
			$("body").append(t.jqpTmpCanvas);
			
			t.jqp_bd = $('<div class="bd"></div>');
			t.jqpTmpCanvas.append(t.jqp_bd);

			if (t.content) {
				if (typeof t.content == 'object') {
					t.jqp_bd.replaceWith(t.content);
					t.jqp_bd = $(t.content);
				}
				else if(typeof t.content == 'string') {
					t.jqp_bd.html(t.content);
				}
			}
			else {
				if (!t.width) t.width = 320;
				t.jqp_bd.load(t.getUrl(), null, function(){  t.hideLoading().replaceCanvas(); });
			}

			if (!t.url && !t.isImage) t.replaceCanvas();
		}
		return this;
	};

	PanelElement.prototype.replaceCanvas = function()
	{
		if (this.jqpTmpCanvas) {
			if (!this.inline) {
				if (this.width) {
					this.jqpTmpCanvas.css('width', this.width);
					this.tmpHeight = this.jqpTmpCanvas.height();
					this.jqpTmpCanvas.css('width', '100%');
				}
				else {
					this.jqpTmpCanvas.addClass('jqp_panel_tmp_canvas');
					this.tmpWidth = this.jqpTmpCanvas.width();
					this.tmpHeight = this.jqpTmpCanvas.height();
					this.jqpTmpCanvas.removeClass('jqp_panel_tmp_canvas');
				}
			}

			this.jqp_canvas.replaceWith(this.jqpTmpCanvas);
			this.jqp_canvas = this.jqpTmpCanvas;
			this.resize().setPlace();
		}
		return this;
	};

	PanelElement.prototype.show = function()
	{
		if (this.error)return this;
		
		if (this.isHide === false) return this.focus();
		
		if (this.opennew && this.url) this.loaded = false;
		this.jqp_panel.show();
		this.isHide = false;
		this.loadContent().focus().resize().setPlace().showMask();

		if (this.type != 'alert' && this.type != 'confirm' && this.callback)this.callback.call(this, 'show');
		if (this.jqp_iframe && typeof this.jqp_iframe.data("onload") == 'function'){
			this.jqp_iframe.data("onload")();
		}
		return this;
	};

	PanelElement.prototype.showMinimiz = function()
	{
		if (this.error)return this;
		
		if (this.isHide === false) return this.focus();

		this.jqp_panel.show();
		this.isHide = false;
		this.setPlace().focus();

		this.jqp_minimiz.removeClass("jqp_minimiz_open");
		this.jqp_minimiz.addClass("jqp_minimiz_close");
		this.jqp_canvas.hide();
		if (this.jqp_ft)this.jqp_ft.hide();
		this.isMin = true;

		if (this.type != 'alert' && this.type != 'confirm' && this.callback)this.callback.call(this, 'showMinimiz');
		return this;
	};

	PanelElement.prototype.minimiz = function ()
	{
		if (this.error)return this;
		if (!this.jqp_minimiz) return this;

		if (!this.isMin){
			this.jqp_minimiz.removeClass("jqp_minimiz_open");
			this.jqp_minimiz.addClass("jqp_minimiz_close");
			this.jqp_canvas.hide();
			if (this.jqp_ft)this.jqp_ft.hide();
			this.isMin = true;
		}
		else {
			this.loadContent();
			this.jqp_minimiz.removeClass("jqp_minimiz_close");
			this.jqp_minimiz.addClass("jqp_minimiz_open");
			this.jqp_canvas.show();
			if (this.jqp_ft)this.jqp_ft.show();
			this.isMin = false;
		}
		this.setUnderlaySize();

		return this;
	};

	PanelElement.prototype.focus = function()
	{
		if (this.error)return this;
		$('.jqp_submit', this.jqp_panel).focus();
		$.JqPanel.currId = this.id;

		if (!this.inline){
			if (this.jqp_mask)this.jqp_mask.css('z-index', $.JqPanel.zIndex++);
			this.jqp_panel.css('z-index', $.JqPanel.zIndex++);
			this.jqp_wrapper.css('z-index', $.JqPanel.zIndex++);
			this.zIndex = $.JqPanel.zIndex;
		}

		return this;
	};

	PanelElement.prototype.close = function(seconds)
	{
		if (this.error)return this;
		var t = this, d = window.document, ix = 0, p;		

		function hide(){
			t.hideMask();
			t.isHide = true;
			if (t.type != 'alert' && t.type != 'confirm' && t.callback)t.callback.call(t, 'close');
		}

		seconds = (!isNaN(seconds)) ? parseInt(seconds) : 'fast';
		if (seconds == 'fast') {
			t.jqp_panel.fadeOut("fast", hide);
		}
		else if (seconds == 0) {
			t.jqp_panel.hide();
			hide();
		}
		else {
			setTimeout(function(){t.jqp_panel.fadeOut("fast", hide);}, seconds * 1000);
		}

		return this;
	};

	PanelElement.prototype.showLoading = function()
	{
		if (this.error)return this;
		if (this.url || this.isImage){
			if (!this.jqp_load) {
				this.jqp_wrapper.append('<div class="jqp_load">&nbsp;</div>');
				this.jqp_load = $(".jqp_load", this.jqp_panel);
			}
			this.jqp_load.show();
		}
		return this;
	}

	PanelElement.prototype.hideLoading = function()
	{
		if (this.error)return this;
		if (this.jqp_load) this.jqp_load.hide();
		return this;
	}

	PanelElement.prototype.doRefresh = function()
	{
		if (this.error)return this;
		if (this.isMin == true || !this.url) return this;

		if (this.jqp_iframe) {
			this.jqp_iframe.attr("src", this.getUrl());
		}
		else this.jqp_bd.load(this.getUrl());

		return this;
	};

	PanelElement.prototype.moveBy = function(left, top)
	{
		if (this.error)return this;
		var t = this,  w, pos={}, i, n, A, firstA, M, firstM, Apos={}, firstApos={}, Mpos={}, firstMpos={};

		if ($.JqPanel.groupAreas.length > 0 && $.JqPanel.groupModules[t.id]){
			for (var n in $.JqPanel.groupAreas){
				A = $.JqPanel.groupAreas[n];
				Apos = {x:A.offset().left, y:A.offset().top, w:A.width(), h:A.height()};
				if (left > Apos.x && top > Apos.y){
					if (!firstApos.x || (firstApos.x < Apos.x || firstApos.y < Apos.y)){ firstA = A; firstApos = Apos; };
				}
			}

			for (var i in $.JqPanel.groupModules){
				M = $.JqPanel.groupModules[i].jqp_panel;
				Mpos = {x:M.offset().left, y:M.offset().top, w:M.width(), h:M.height()};
				if (t.id != i && top > Mpos.y && (firstApos.x && Mpos.x > firstApos.x && Mpos.x < firstApos.x+firstApos.w && Mpos.y > firstApos.y && Mpos.y < firstApos.y+firstApos.h)){
					if (!firstMpos.x || (firstMpos.x < Mpos.x || firstMpos.y < Mpos.y)){ firstM = M, firstMpos = Mpos; }
				}
			}

			if (firstM)firstM.after(t.jqp_panel);
			else if (firstA) firstA.prepend(t.jqp_panel);
		}
		else t.jqp_panel.css({left:left, top:top});

		return this;
	};

	PanelElement.prototype.setUnderlaySize = function()
	{
		if (this.error)return this;
		if (this.jqp_underlay) {
			this.jqp_underlay.css({"width":this.jqp_wrapper.outerWidth(true)+6, "height":this.jqp_wrapper.outerHeight(true)});
		}
	};

	PanelElement.prototype.resize = function(dw, dh)
	{
		if (this.error)return this;
		if (this.inline) dw = "100%";
		if (dw != undefined) this.width = dw;
		if (dh != undefined) this.height = dh;
		if (dw === '' || dw === 0) this.tmpWidth = 0;
		if (dh === '' || dh === 0) this.tmpHeight = 0;

		var w, h, vp = $.Dom.getViewPort();
		w = this.width > 0 ? this.width : this.tmpWidth;
		if (!this.inline){
			if (w > vp.w - 30) w = vp.w - 30;
			if (w < this.minWidth) w = this.minWidth;
		}
		this.jqp_panel.css("width", w);

		h = this.height > 0 ? this.height-this.hd_height-this.ft_height : this.tmpHeight;
		if (h > vp.h - 60) this.jqp_canvas.css("height", vp.h - 60);
		else if (h < this.minHeight) this.jqp_canvas.css("height", this.minHeight);
		else if (this.height > 0) this.jqp_canvas.css("height", this.height-this.hd_height-this.ft_height);

		this.setUnderlaySize();

		return this;
	};

	PanelElement.prototype.setPlace = function()
	{
		if (this.error)return this;
		if (this.type == 'dropdown' || this.type == 'context' || (this.context && this.context[0])) {
			var opt_xy={};
			if (this.context && this.context[0]) opt_xy = $.Dom.getContextXY(this.jqp_panel, this.context[0], this.context[1]);
			else if (this.left && this.top) opt_xy = $.Dom.getContextXY(this.jqp_panel, null, null, {x:this.left, y:this.top});
			if (opt_xy.x && opt_xy.y){
				this.jqp_panel.css({top:opt_xy.y, left:opt_xy.x});
			}
		}
		else if (this.inline){
			this.jqp_panel.css({top:0, left:0, marginLeft:0, marginTop:0});
		}
		else {
			this.jqp_panel.css({top:this.top||'50%', left:this.left||'50%', marginLeft:-Math.round(this.jqp_panel.width() / 2.0)+$(document).scrollLeft(), marginTop:-Math.round(this.jqp_panel.height() / 2.0)+$(document).scrollTop()});
		}

		return this;
	};

	PanelElement.prototype.useIframe = function(bool)
	{
		this.iframe = bool ? true : false;
		return this;
	};

	PanelElement.prototype.getUrl = function(){
		if (this.url){
			return this.url + (this.url.indexOf('?') == -1 ? '?' : '&') + 'panelId=' + this.id + '&random=' + (new Date().getTime()+Math.random());
		}
		return '';
	};

	function getParams(obj, params)
	{
		var opt = {}, title, url;
		obj = $(obj);
		if (title = obj.attr("title")) opt.title = title;
		if (url = obj.attr("href")) opt.url = url;
		if (params) opt = $.extend(opt, params);
		return opt;
	}

	$.fn.extend({
		panel: function(opt) {
			return this.each(function() {
				opt = getParams(this, opt);
				$(this).click(function(){ $.JqPanel.panel(opt); this.blur(); return false; });
			});
		},
		dropdown: function(opt, ifDropDownHandler) {
			return this.each(function() {
				opt = getParams(this, opt);
				$.JqPanel.dropdown(this, opt, ifDropDownHandler);
			});
		},
		context: function(opt, ifContextHandler) {
			return this.each(function() {
				opt = getParams(this, opt);
				$.JqPanel.context(this, opt, ifContextHandler);
			});
		},
		moduleGroup: function() {
			$.JqPanel.moduleGroup(this, arguments);
		}
	});
})();
