﻿/// <reference path="http://js.tgimg.cn/jquery/1.4/jquery.min.js" />
(function($, window){
	debugopen = false;
	_debug = function(fun){
		if(debugopen){
			if($.isFunction(fun)){
				fun();
			}else if(typeof fun === "object"){
				var msg = "";
				for(var n in fun){
					msg += n + ":" + fun[n] + "\n";
				}
				alert(msg);
			}else {
				alert(fun);
			}
		}
	};
})(jQuery, window);
//ie6缓存背景图片
if ($.browser.msie && $.browser.version == "6.0")
    document.execCommand("BackgroundImageCache", false, true);	
	
(function($){
	$.ajaxSetup({
		error: function(){
			_debug("网络错误,请稍候重试!");
		}
	});
	$.extend({
		lock: function(){
			for(var i = arguments.length - 1; i >= 0; i--){
				var e = arguments[i];
				if(!(e instanceof $)) e = $(e);
				if(e.is("input"))
					e.attr("disabled", true);
			}
		},
		unlock: function(){
			for(var i = arguments.length - 1; i >= 0; i--){
				var e = arguments[i];
				if(!(e instanceof $)) e = $(e);
				if(e.is("input"))
					e.attr("disabled", false);
			}
		}
	})
	
	var globalsAjaxData = {}, // 对于事件的全局 ajax 对象
		guid = 0; // 对于事件的全局 ajax 标识			
	$.fn.extend({
		removeAjax: function( type ){
			return this.each(function(){
				var $this = $(this), ids = $this.data("ajaxSourceIDs") || {}, g;
				if(ids[ type ] && ( g = globalsAjaxData[ ids[ type ] ] )){
					globalsAjaxData[ ids[ type ] ] = null;
				}
			});
		},
		addAjax: function( type, _options, cache, lock, connectInput){	
			var options = createOptions( _options );			
			cache = cache === undefined ? false : cache;
			lock = lock === undefined ? true : lock; //是否显示加载中样式
			connectInput = connectInput instanceof Array ? (function(){
				var r = $();
				for(var i = 0; i < connectInput.length; i++){
					$.merge(r, $(connectInput[i]));
				}
				return r;
			})() : $(connectInput);

			var id = 'typeAjax_' + guid++, _this = this, s = options.success, e = options.error, sr, beforeSend = options.beforeSend;
			if($.isFunction(beforeSend)){
				options.beforeSend = function(){
					var r = beforeSend.call(this, globalsAjaxData[id].e);
					if(r === false){
						globalsAjaxData[id].state = 0;
						if (globalsAjaxData[id].lock) {
							unlockSource(globalsAjaxData[id].e);
						}
						if(globalsAjaxData[id].connect)$.unlock(globalsAjaxData[id].connect);
					}
					return r;
				}
			}
			options.success = function(){
				var data = arguments[0];
				if (data && data.State === 0) {
					globalsAjaxData[id].data = arguments[0];
					globalsAjaxData[id].state = 2;
				}else{
					globalsAjaxData[id].data = null;
					globalsAjaxData[id].state = 0;
				}
				if(data && data.Msg === undefined)
					data.Msg = "未知错误！";
				sr = s.apply(this, arguments);
				if(sr !== undefined){ //当存在返回值且请求已完成响应后，强制缓存
					globalsAjaxData[id].cache = true;
				}	
				if (sr !== false && globalsAjaxData[id].lock) {					
					if(globalsAjaxData[id].connect)$.unlock(globalsAjaxData[id].connect);
					unlockSource(globalsAjaxData[id].e);
				}
			}
			options.error = function(){
				globalsAjaxData[id].state = 0;
				e.apply(this, arguments);
				if (globalsAjaxData[id].lock) {
					unlockSource(globalsAjaxData[id].e);
				}
				if(globalsAjaxData[id].connect)$.unlock(globalsAjaxData[id].connect);
			}
			globalsAjaxData[id] = {
				id: id,
				cache: cache,
				// 0为未请求,1为请求中,2为已经响应并返回数据
				state: 0,
				//返回的数据
				data: null,
				//关联的输入控件，提交的时候，必定提交这些数据
				connect: connectInput.length ?  connectInput : null,
				options: options, 
				e: _this,
				lock: lock
			};						
			return this.each(function(){	
				var $this = $(this), a = $this.data("ajaxSourceIDs") || {};
				if(a[type])
					globalsAjaxData[a[type]] = null;
				a[type] = id;				
				$this.data("ajaxSourceIDs", a);
			});
		},
		hasAjax: function( type ){
			var has = true;
			if($(this).length){
				this.each(function(){
					var $this = $(this), a = $this.data("ajaxSourceIDs");
					if(a && a[type] && globalsAjaxData[a[type]]){
						return true;
					}else{
						has = false;
						return false;
					}
				});				
			}else{
				has = false;
			}
			return has;
		},
		sendAjax: function( type, data ){
			var rDeferred;
			if(typeof type == "string")
				this.each(function(){				
					var $this = $(this), a = $this.data("ajaxSourceIDs"), g, update = false, connectError = false;
					if(a && a[type] && ( g = globalsAjaxData[a[type]] )){
						if(g.connect){
							data = data || {};
							g.connect.each(function(){
								var $c = $(this);								
								if ($c.is(":text,:password,select,textarea,:checked,[type=hidden]")) {
									var cValue = $.trim($c.val()), cTitle = $c.attr("empty-msg") || $c.attr("title");
									if (!cValue && cTitle) {
										alert(cTitle);
										connectError = true;
										$c.focus();
										return false;
									}
									data[$c.attr("name")] = encodeURIComponent(cValue);
								}
							});
							if(connectError)
								return;
						}
						if (data !== undefined) {
							if (g.cache) {
								if(typeof(data) == "object")
									for (var n in data) {
										if (data[n] !== g.options.data[n]) {
											update = true;
											g.options.data = data;
											break;
										}
									}
								else if( data !==  g.options.data){
									update = true;
									g.options.data = data;
								}
							}else 
								g.options.data = data;
						}
						g.options.data.op = type;
						if(update || g.state === 0 || (g.state === 2 && !g.cache)){
							if (g.lock) {
								lockSource(g.e, g.lock);
							}
							if(g.connect) $.lock(g.connect);
							g.state = 1;
							rDeferred = $.ajax( g.options );
						}else if(g.state === 2 && g.cache){
							if (g.lock) {
								lockSource(g.e, g.lock);
							}
							if(g.connect) $.lock(g.connect);
							rDeferred = $.when(g.options.success(g.data));
						}
					}
				});
			else if(typeof type == "object"){
				var $this = $(this), sending;
				$this.each(function(){
					sending = $(this).data("sendingAjaxDeferred")
					if (sending) {
						return false;
					}
				});	
				if(sending){
					return sending;
				}
				type = createOptions(type);
				var s = type.success, 
					e = type.error,
					lockStr = data === undefined ? true : data;
				type.success = function(){
					$this.data("sendingAjaxDeferred", null);
					if(s.apply(this, arguments) !== false && lockStr)
						unlockSource($this);
				}
				type.error = function(){
					$this.data("sendingAjaxDeferred", null);
					e.apply(this, arguments);					
					if(lockStr)
						unlockSource($this);
				}
				if(lockStr)
					lockSource($this, lockStr);
				rDeferred = $.ajax(type);
				$this.data("sendingAjaxDeferred", rDeferred);
			}
			return rDeferred;
		}
	});	
	function unlockSource(elems){
		$(elems).each(function(){
			var $this = $(this), 
				input = $this.is("input"),
				text = $this.data("ajaxSourceText");
			if(input){
				$this.val(text);
			}else{
				var c = $this.children();			
				if(c.length){
					c.html(text);
				}else{
					$this.html(text);
				}	
			}
		});
	}	
	function lockSource(elems, str){
		str = typeof str == "string" ? str : "加载中.." ;
		$(elems).each(function(){
			var $this = $(this),
			 	input = $this.is("input"),
				text;
			if(input){
				text = $this.val();
				$this.val(str);
			}else{
				var c = $this.children(":visible");			
				if(c.length && c.html().length){
					text = c.html();
					c.html(str);
				}else{
					text = $this.html();
					$this.html(str);
				}				
			}
			$this.data("ajaxSourceText", text);
		});
	}	
	function createOptions( options ){
		var o = {};
		$.extend( o, options);
		if(!o.dataType) o.dataType = "text json";
		if(!o.type) o.type = "post";
		if(!o.url) o.url = "/System/AjaxService.aspx";
		if(!o.success) o.success = function(){};
		if(!o.error) o.error = function(){alert("网络繁忙,请稍候重试!");};
		if(!o.data) o.data = {};
		return o;
	}	
})(jQuery);
//JS警告框

(function ($) {
	$.extend({
		alertBtn:{
			OK: parseInt("0001", 2),
			CANCEL: parseInt("0010", 2),
			YES: parseInt("0100", 2),
			ON: parseInt("1000", 2)
		},
		alert: function(content, title, btnType, clickHandler){
			if(!content)return;				
			var eConent = $("<div/>").css({
				"padding": "10px 20px"
			}),
			eTitle = $("<h2/>").css({
				"padding": "5px 10px",
				"background":"#e1e1e1"
			}),
			eBtnArea = $("<div/>").css({
				"padding": "10px",
				"text-align": "center"
			}),
			eBtn = $("<button/>").css({
				"margin": "0 5px",
				"cursor": "pointer",
				"width": "60px",
				"height": "30px"
			}),
			eArea = $("<div/>").css({
				"position": "absolute",
				"border" : "1px #a1a1a1 solid",
				"z-index":"99999",
				"background":"#fff"
			}).append(eTitle).append(eConent).append(eBtnArea),
			eOk,
			eCancel,
			eYes,
			eNo,
			timer,
			w = window.parent ? window.parent : window,
			wHeiget = $(w).height() < 400 ? 400 : $(w).height(),
			wWidth = $(window).width(),
			wTop = $(w.document).scrollTop(),
			top,
			left;
			if(title){
				eTitle.html(title);
			}else{
				eTitle.html("&nbsp;");
			}
			eConent.html(content);			
			
			if(btnType & $.alertBtn.OK){
				eBtnArea.append(eBtn.clone().text("确定").data("type", $.alertBtn.OK));
			}
			if(btnType & $.alertBtn.CANCEL){
				eBtnArea.append(eBtn.clone().text("取消").data("type", $.alertBtn.CANCEL));
			}
			if(btnType & $.alertBtn.YES){
				eBtnArea.append(eBtn.clone().text("是").data("type", $.alertBtn.YES));
			}
			if(btnType & $.alertBtn.NO){
				eBtnArea.append(eBtn.clone().text("否").data("type", $.alertBtn.NO));
			}
			if(!eBtnArea.children().length){
				eBtnArea.append(eBtn.clone().text("确定").data("type", $.alertBtn.OK));
			}
			eBtnArea.bind("click", function(event){
				var target = $(event.target);
				if(target.is("button")){
					eArea.stop(true);
					event.detail = target.data("type");
					if($.isFunction(clickHandler))
						clickHandler.call(event.target ,event);			
					eArea.remove();
				}
			});
						
			
			if(eArea.width() < 250)
				eArea.width(250);
			if(eArea.width() > 550)
				eArea.width(550);
				
			$("body").append(eArea);
			
			top = Math.max( ( wHeiget - eArea.height() ) / 2, 0) + wTop;
			left = Math.max( ( wWidth - eArea.width() ) / 2, 0);
			eArea.css({"top":top + "px","left":left + "px"});
			
			//拖动
			eArea.easydrag(eTitle);
			
			
			return eArea;
		},
		alertLimit: function(content, title, btnType, clickHandler, time, timeOverHandler){
			var eArea, cf, tf, bt, ti, t, timer = null;			
			if($.isFunction(title)){
				t = "";
				cf = title;
				if($.isFunction(btnType))
					tf = btnType;
				else if(btnType != undefined){
					bt = btnType;
					if(clickHandler != undefined){
						if ($.isFunction(clickHandler)) {
							tf = clickHandler;
							ti = 1500;
						}else{
							ti = parseInt( clickHandler );
							if($.isFunction(time))
								tf = time;
							else
								tf = cf;
						}
					}
				}else{
					tf = cf;
				}
			}else{
				t = title;
				bt = btnType;
				cf = clickHandler;
				ti = time;
				tf = timeOverHandler;
			}			
			eArea = $.alert(content, t, bt, function(event){
				clearTimeout(timer);
				if($.isFunction(cf))
					cf.call(this ,event)
			});			
			function close(){				
				timer = null;
				eArea.stop(true).animate({
					opacity: "hide"
				},function(){
					if($.isFunction(tf))		
						tf.call(eArea);
					eArea.remove();
				});
			}
			eArea.hover(function(){
				clearTimeout(timer);
				eArea.stop(true).css("opacity", 1);
			}, function(){				
				timer = setTimeout(function(){
					close();
				}, ti ? ti : 1500);
			}).triggerHandler("mouseout");
		}
	});
})(jQuery);

//加载JS文件并缓存

(function($) {
    $.extend({
        JsLoader: function(src, callback, cache, deferred) {
			if(callback === undefined || typeof(callback) == "boolean"){
				deferred = cache;
				cache = callback;
				callback = function(){};
			}else if(!$.isFunction(callback) && typeof(callback) == "object"){
				deferred = callback;
				cache = true;
				callback = function(){};
			}
			if (typeof src == "string") {
				var successFun = callback;
				if(deferred){
					successFun = function(){
						callback.apply(this, arguments);
						deferred.resolve();
					}
				}					
				return $.ajax({
					url: src,
					success: successFun,
					cache: cache === undefined ? true : cache,
					dataType: "script"
				});
			}
			else 
				if (src instanceof Array) {
					var rDeferred,
						d = $.Deferred();				
					rDeferred = (function(num, d){
						if (num < src.length) {
							var _d = $.Deferred(),
								_cache = cache;
							d.done(function(){
								$.JsLoader(src[num], _cache, _d)
							});
							return arguments.callee(num + 1, _d);
						}
						return d;
					})(1, d);
					rDeferred.done(callback);
					$.JsLoader(src[0], cache, d);			
					return rDeferred;
				}
        }
    });
})($);

//拖动
(function($){
	var drayData = [], start = false, x = 0, y = 0, timer = null, wWidth = 0, wHeight = 0, moveBegin = null, moveEnd = null,
		instead = $("<div/>").css({
			"position": "absolute",
			"border": "2px #999 solid",
			"cursor": "move"
		});
	
	$(document).bind("mousemove.easydrag", function(event){
		if (start) {
			var event = event;
			clearTimeout(timer);
			timer = setTimeout(function(){
				move(event);
			}, 2);
		}
	}).bind("mousedown.easydrag", function(event){
	}).bind("mouseup.easydrag", function(){
		if (start) {
			start = false;
			$.each(drayData, function(){
				var $this = this.e;
				if ($this.data("easydray")) {
					$this.data("easydray", false);
					$this.unbind("selectstart.easydrag").css("-moz-user-select", "inherit").attr("unselectable", $this.data("unselectable"));
					$this.css({
						top: this.y,
						left: this.x
					});
					instead.detach();
				}
			});
		}
	});
	
	function move(event){
		var pX = event.pageX, pY = event.pageY;
		pX  = pX < 0 || pX > wWidth ? x : pX;
		pY = pY < 0 ? y : pY;
		$.each(drayData, function(){
			var $this = this.e;
			if ($this.data("easydray")) {
				var w = $this.width(), h = $this.height()
				this.x += pX - x;
				this.y += pY - y;
				this.x = Math.max(0, Math.min(this.x, wWidth - w));
				this.y = Math.max(0, Math.min(this.y, wHeight - h));
				instead.css({
					top: this.y,
					left: this.x
				});
			}
		});
		x = event.pageX;
		y = event.pageY;
	}
	
	$.fn.easydrag = function(handler){
		return this.each(function(){
			var $this = $(this), offset,
				data = {};
			$this.css("position", "absolute");
			(handler ? $(handler) : $(".topBar", this).length > 0 ? $(".topBar", this) : $(this)).css("cursor", "move").unbind("mousedown.easydray").bind("mousedown.easydray", function(event){
				var attrUnselect = $this.attr("unselectable") || "off";				
				$this.data("easydray", true).data("unselectable", attrUnselect);
				$this.css("-moz-user-select", "none").attr("unselectable", "on").bind("selectstart.easydrag", function(){return false;});				
				start = true;
				x = event.pageX;
				y = event.pageY;
				wWidth = $(window).width() - 5;
				wHeight = $(document).height();
				offset = $this.offset();	
				data.x = offset.left;
				data.y = offset.top;
				$this.after(instead.css({
					width: $this.outerWidth() - 2 + "px",
					height: $this.outerHeight() - 2 + "px",
					"z-index" : parseInt($this.css("z-index")) + 1,
					top: offset.top + "px",
					left: offset.left + "px"
				}));
			});
			data.e = $this;
			drayData.push(data);
		});			
	}
})(jQuery);
(function($){
	var isIE = $.browser.msie, isIE6 = isIE && $.browser.version == "6.0",
		popElementList = [], //弹出队列
		currentPopObj = null, //当前弹出窗口的Obj
		layer = $("<div/>").css({ //遮罩层
            left: 0,
            top: 0,
            background: "#fff",
            opacity: "0.5",
            width: "100%",
            zIndex: 1001,
            position: "absolute"
        }),
		loading = $("<span/>").css({
	        "width": "250px",			
			"display": isIE ? "inline" : "inline-block",
			"zoom": 1,
			"padding-left": "25px",
			"position": "absolute",
			"font-size": "14px",
			"z-index": 1002,
	        "background": "url(http://img.tgimg.cn/common/loading.gif) no-repeat 0 center"
	    }).html("数据加载中,请稍后.");
	//打开 和 关闭 动画
	var _showMaskFun = (function(){
			return isIE6 ? function( popDiv ){
				popDiv.toggle(true);
			} : function( popDiv ){
				popDiv.css("opacity", "0").toggle(true);
			}
		})(), 
		_showMaskAinmate = (function(){
			return isIE6 ? function( popDiv, callBack ){
				popDiv.stop(true).animate({ top: "+=20" }, callBack)
			} : function( popDiv, callBack ){
				popDiv.stop(true).animate({ top: "+=20", "opacity": "1" }, callBack);
			}
		})(),
		_hideMaskFun = (function(){
			return isIE6 ? function( popDiv ){
				popDiv.toggle(false);
			} : function( popDiv ){
				popDiv.css("opacity", "1").toggle(false);
			}
		})(),
		_hideMaskAinmate = (function(){
			return isIE6 ? function( popDiv, callBack ){
				popDiv.stop(true).animate({ top: "+=20" }, 300, callBack)
			} : function( popDiv, callBack ){
				popDiv.stop(true).animate({ top: "+=20", opacity: 0 }, 300, callBack);
			}
		})();
	function formatObj( e, obj ){
		var _obj;
		if($.isFunction(obj)){
			_obj = {};
			_obj.complete = obj;
		}else{
			_obj = obj || {};
		}
		_obj.e = $(e);
		if(_obj.z === undefined)_obj.z = 0;
		if(_obj.later === undefined) _obj.later = false;
		if(_obj.findForm === undefined) _obj.findForm = false;
		if(_obj.deferredCache === undefined)_obj.deferredCache = false;
		return _obj;
	}
	if (isIE6) {
		var docReady = false;
		$(function(){
			docReady = true;
			if(popElementList.length)
				triggerObj(popElementList.shift());
		});
	}
	function middleOffset( $this ){		
		var winHeight, winParentScrollTop;
        if (window.parent && window.parent != window) {
            winHeight = $(window.parent).height();
            winParentScrollTop = $(window.parent).scrollTop();
        }else{
			winHeight = $(window).height();
			winParentScrollTop = 0;
		}
		return {
			top: Math.max((winHeight - $this.height()), 0) * 2 / 5 + $(document).scrollTop() + winParentScrollTop,
			left: $(window).width() / 2 - $this.width() / 2
		};		
	}
	function triggerObj( obj ){
		var $this = $(obj.e), defferrd = $this.data("mask-deferred-obj");		
		layer.css({
            height: $(document).height()
        }).pop(0, 0).toggle(true);
		loading.appendTo("body").css(middleOffset(loading));
		defferrd.fail(function(){
			loading.detach();
			alert("数据加载出错,请尝试按Ctrl+F5刷新页面或稍后再试或联系客服解决!");
			layer.toggle(false);
		}).done(function(){
			loading.detach();
			if($.isFunction(obj.open))
				$this.one("mask-open", obj.open);
			if($.isFunction(obj.complete))
				$this.one("mask-complete", obj.complete);
			if($.isFunction(obj.exit))
				$this.one("mask-exit", function(event){
					obj.exit.apply(this, [event, obj.data]);
				});
			if($.isFunction(obj.close))
				$this.one("mask-close", function(event){
					obj.close.apply(this, [event, obj.data]);
				});
			if ($this.data("mask-once") !== false) {
				if($.isFunction(obj.format))
					obj.format();
				$this.triggerHandler("mask-format");
				$this.data("mask-once", false);
			}
			currentPopObj = obj;
			$(".topBar", $this).each(function(){				
				$this.easydrag(this);
				$(".span_close", this).unbind("mousedown.easyDray").bind("mousedown.easyDray", function(event){
					event.stopPropagation();
				});
			});
			$(".span_close", $this).unbind("click.mask-span-close").bind("click.mask-span-close", function(event){
				$this.unmask();
			});
			if (obj.findForm !== false) 
				$("form").eq(parseInt(obj.findForm)).append($this);
			else {
				$("body").append($this);
			}
			$this.triggerHandler("mask-open", obj.data);
			_showMaskFun($this);
			var offset = middleOffset($this);
			$this.css({ "top": offset.top - 20, "left": offset.left, zIndex: 20000 });
			_showMaskAinmate($this, function(){
				$this.triggerHandler("mask-complete", obj.data);
			});			
		});		
	}
	$.fn.extend({
		/**
		 * 参数 obj 
		 * 如果为Function为Complete时执行的方法
		 * 
		 * 如果为object,可以包含以下属性
		 * open 执行打开动画前调用 对应 mask-open 事件
		 * complete 打开动画完结后调用 对应 mask-complete 事件
		 * exit 退出动画执行前调用 对应  mask-exit 时间
		 * close 退出动画执行完结后调用 对应 mask-close 事件
		 * format 初次打开是执行的方法
		 * later 为true时, 如果当前有弹出层,则等现有弹出层关闭后再弹出; 为false时,直接替换现有弹出层; 默认为false
		 * z 优先级,默认为0;只有later为true时才有效
		 * findForm 是否往form表单插入弹出层,默认未false, 当为数字时向form插入, form下标由0开始
		 * data: mask-open, mask-complete, mask-exit, mask-close事件要接收的第二参数
		 */
		popup: function( inobj ){
			var obj = formatObj(this, inobj), $this = $(this), deferred = $this.data("mask-deferred-obj"), deferredCache = obj.deferredCache;
			if($this.length == 0)return this;
			$this.css("position", "absolute").toggle(false);
			if (!deferred) {
				deferred = $.Deferred();
				$this.data("mask-deferred-obj", deferred);
				deferredCache = false;
			}
			if(!deferredCache){
				$.when($.isFunction(obj.deferred) ? obj.deferred() : obj.deferred).then(deferred.resolve, deferred.reject);
			}
			if(obj.later && (currentPopObj || popElementList.length > 0)){
				for(var i = 0; i < popElementList.length; i++){
					if(popElementList[i].z < obj.z)
						popElementList.splice(i, 0, obj);
				}
				if(i == popElementList.length)
					popElementList.push(obj);
			}else {				
				if(isIE6 && !docReady){
					for(var i = 0; i < popElementList.length; i++){
						var o = popElementList[i];
						if(o.later || o.z < obj.z)
							popElementList.splice(i, 0, obj);
					}
					if(i == popElementList.length)
						popElementList.push(obj);
				}else{
					popElementList.splice(0, 0, obj);
					if (currentPopObj) 
						$(currentPopObj.e).unmask();
					else {
						triggerObj(popElementList.shift());
					}
				}		
			}
			return this;
		},
		unmask: function( callback ){
			var $this = $(this);
			if ($this.length) {
				if(currentPopObj && $this.get(0) == $(currentPopObj.e).get(0))	
					currentPopObj = null;
				$this.triggerHandler("mask-exit");
				if (popElementList.length > 0) {
					$this.stop(true).toggle(false);
					$this.triggerHandler("mask-close");
					if($.isFunction(callback))
						callback();
					triggerObj(popElementList.shift());
				}else{
					_hideMaskAinmate($this, function(){
						_hideMaskFun($this);
						$this.triggerHandler("mask-close");
						if($.isFunction(callback))
						callback();
						layer.toggle(false);
					});
				}					
			}
			return this;			
		},
		backToMiddle: function() {
	        var $this = $(this),
	         	top = $(window).height() / 2 - $this.height() / 2 + $(document).scrollTop(),
	        	left = $(window).width() / 2 - $this.width() / 2,
				obj = { "top": top, "left": left };
			if(!isIE6){
				obj.opacity = 1;
			}
	        $this.stop(true).animate(obj);
	    },
		popupLater: function( inobj ){
			var obj = formatObj(this, inobj);
			obj.later = true;
			return $(this).popup(obj);
		},
		mask: function( inobj, formNum ){
			var obj = formatObj(this, inobj);
			obj.findForm = formNum === false ? false : 
								formNum === undefined ? 0 :
									!isNaN(formNum) ? formNum : 0;
			return $(this).popup(obj);
		},
		pop: function(left, top, parent, iframePop) {
			var ifPop = iframePop === undefined ? true : iframePop;
	        return $(this).each(function() {
	            var e = $(this);
	            if (left !== undefined)
	                e.css({ top: top, left: left }).appendTo(parent ? parent : "body");		
				if (ifPop) {
					var iframe = $("iframe.popIframe", e), iframeMask = $("div.popIframeMask", e); //兼容document事件
					if (iframeMask.length == 0) {
						iframeMask = $("<div/>").css({
							"position": "absolute",
							"top": 0,
							"left": 0,
							"z-index": "-1"
						}).prependTo(e).addClass("popIframeMask");
					}
					else {
						iframeMask.prependTo(e);
					}
					if (iframe.length == 0) {
						iframe = $("<iframe scrolling='no' frameborder='0'/>").css({
							"position": "absolute",
							"top": 0,
							"left": 0,
							"z-index": "-2",
							"opacity": 0
						}).addClass("popIframe").prependTo(e);
					}
					iframe.width(e.get(0).offsetWidth || e.width()).height(e.get(0).offsetHeight || e.height());
					iframeMask.width(e.get(0).offsetWidth || e.width()).height(e.get(0).offsetHeight || e.height());
				}
	        });
	    }
	})
	
})(jQuery);

(function($){
	//当点击绑定的元素和元素本身之外的其他元素时,隐藏元素	
	var elemsData = [];
	$.fn.docClickHide = function (opts) {
		if(opts && opts["handle"]){
			this.exceptClickHide(opts["handle"]);
		}
		return this;
	}
	$.fn.exceptClickHide = function(){
		var arg = arguments, elems = $(), $this = $(this), _this = $this.get(0),
			openFun, closeFun, 
			s = false, //为False时,点击elems不会关闭;为True时,当对象打开时,点击elems会关闭
			add = true; //元素是否不重复

		for(var i = 0, j = arg.length; i < j; i++){
			if(typeof(arg[i]) == "boolean"){
				s = arg[i];
			}else if( $.isFunction(arg[i]) && !(arg[i] instanceof $) ){
				!openFun ? (openFun = arg[i]) : (closeFun = arg[i]);
			}else if(arg[i].nodeType == 1 || arg[i] instanceof $){
				$.merge(elems, $(arg[i]));
			}		
		}
		for(var i = elemsData.length - 1; i >= 0; i--){
			if(elemsData[i].elem === _this){
				$.merge(elemsData[i].handle, elems);
				add = false;
			}
		}
		if( add )
			elemsData.push({
				elem: _this,
				$elem: $this,
				handle: elems,
				s: s,
				openFun: openFun || function(){},
				closeFun: closeFun || function(){},
				lastTarget: null
			});
		return this;
	}
	$(document).bind("click.exceptClickHide",function(e){
		if (elemsData.length > 0) {
			var _target = $(e.target).get(0);
			$.each(elemsData, function(){
				var $this = this.$elem, _this = this.elem, elems = this.handle, s = this.s, openFun = this.openFun, closeFun = this.closeFun, lastTarget = this.lastTarget;
				if ($this.css("display") != "none") {
					var close = true, inElems = false, closeTargetBtn, target = $(_target);
					elems.each(function(){
						closeTargetBtn = $(this);
						if (closeTargetBtn.get(0) == _target || closeTargetBtn.has(_target).length > 0) {
							close = s;
							inElems = true;
							return false;
						}
					});
					if(inElems && lastTarget != closeTargetBtn.get(0) && $this.has(closeTargetBtn).length == 0){
						this.lastTarget = closeTargetBtn.get(0);
						openFun.call($this, closeTargetBtn);
						close = false;
					}
					if (close && (_target == _this || $this.has(_target).length > 0)) {
						close = inElems ? s : false;
					}
					if (close && closeFun.call($this, target) !== false) {
						this.lastTarget = null;
						$this.toggle(false);
					}
				}else {
					var show = false, showTargetBtn;
					elems.each(function(){
						showTargetBtn = $(this);
						if (showTargetBtn.get(0) == _target || showTargetBtn.has(_target).length > 0) {
							show = true;
							return false;
						}
					});
					if (show && openFun.call($this, showTargetBtn) !== false) {
						this.lastTarget = showTargetBtn.get(0);
						$this.toggle(true);
					}
				}
			});
		}
	});
})(jQuery);

(function($){
	var keypressEvents = $.browser.version == "6.0" && $.browser.msie ? "keypress" : "keydown";
	
	$.each(["enter", "ctrlEnter", "backspace"], function( i, name){
		var key = name;
		$.fn[key] = function( fn ){
			return !fn || $.isFunction( fn ) ? 
				this[fn ? "bind" : "trigger"]( key, fn ) :
					this["bind"]( key, function(){ $( fn ).trigger("click"); }); //兼容以前的enter代码
		};		
		$.event.special[key] = {
			setup: function(){
				$.event.add( this, keypressEvents, enterHandler, {type: key} );
			},
			teardown: function(){
				$.event.remove( this, keypressEvents, enterHandler );
			}
		};
	});	
		
	function enterHandler( event ){
		var pass = true;
		switch(parseInt(event.which)){
			case 13:
				if( (event.data.type != "ctrlEnter" && event.data.type != "enter") ||
					(event.data.type == "ctrlEnter" && !event.metaKey) ||
					(event.data.type == "enter" && event.metaKey) )
					pass = false;
				break;	
			case 8:
				if(event.data.type != "backspace")
					pass = false;
				break;
			default:
				pass = false;
		}
		if (pass) {
			event.type = event.data.type;
			return $.event.handle.call(this, event);
		}
	}
})(jQuery);

//input action
(function($, window){
	
	$.extend($.fn, {		
		//input keyword
		keywords: function (opts, extra) {
		    var opts = opts, strDefault = "", $this = $(this), val = $this.val(), color = "#000", color2 = "#888", color3 = "#d0d0d0", c;
		    if(opts && typeof opts == "string"){
		        strDefault = opts;
		    } else if(opts && typeof opts == "object"){
		        strDefault = opts["key"];
				color = opts["focusColor"] || color;
				color2 = opts["blurColor"] || color2;
				color3 = opts["inputColor"]  || color3;
		    }
			if(!strDefault || $this.data("defaultValue") == strDefault){
				return this;
			}
			$this.data("defaultValue", strDefault);
			if(extra === undefined){
				extra = $this.prev("span.grace");
				if(extra.length && extra.data("keywordsHasFormat")){
					extra.html(strDefault);
					return this;
				}
				extra.data("keywordsHasFormat", true);
			}
			if ((extra instanceof $ && extra.length)  || (extra = $(extra)).length) {
				var timerFocus = null, timerKeyup = null, extraShow = false, isDefault = false, 
					oHeight = $this.outerHeight() - 2, 
					oLineHeight = oHeight,
					isInput = $this.is("input"), 
					oWidth = $this.outerWidth() - 12;//border + padding = 12
				extra.css("-moz-user-select", "none").attr("unselectable", "on").bind("selectstart.easydrag", function(){return false;});
				if($.browser.msie)
					oLineHeight += 2;
				extra.html(strDefault).css({
					"color": color2,
					"height": (isInput ? oHeight : oHeight - 3) + "px",
					"width" : oWidth +"px",
					"line-height" : isInput ? (oLineHeight + "px") : "1.25em",
					"padding-top": isInput ? "" : $this.css("padding-top")
				}).toggle(false);
				extra.click(function(){$this.focus();});	
				function keywordsEmptyOrDefault(val){
					if(val == strDefault){
						isDefault = true;
						$this.val("");
					}else{
						isDefault = false;
					}
					if(!val || isDefault){								
						show(isDefault ? color : color2);
						return true;
					}else{
						return false;
					}
				}
				function show(color){
					extraShow = true;
					extra.css({
						"color": color || color3,
						"opacity": 1
					}).toggle(true);
				}
				var hide = (function (){
					if($.browser.msie && $.browser.version == "6.0"){
						return function(){							
							extraShow = false;
							extra.stop(true).css("opacity", 0).toggle(false);
						}
					}else{
						return function(){							
							extraShow = false;
							extra.stop(true).fadeOut(100);
						}
					}
				})();
				$this.bind("keyup.keywords", function(){
						var _this = this;
						clearTimeout(timerKeyup);
						timerKeyup = setTimeout(function(){
							if (!extraShow) {
								if(!$.trim($(_this).val())){
									show();
								}
							}
						}, 200);
				}).bind("blur.keywords", function(){
					var val = $.trim($(this).val());
					clearInterval(timerFocus);
					clearTimeout(timerKeyup);
					if(!keywordsEmptyOrDefault(val)){	
						hide();
					}					
				}).bind("focus.keywords", function(){	
					var _this = this;
					extra.css("color", color3);
					clearInterval(timerFocus);
					timerFocus = setInterval(function(){
						if (extraShow) {					
							var $this = $(_this), val = $.trim($this.val());
							if(val){
								hide();
							}
						}
					}, 50);
				}).triggerHandler("blur");
				return $this;			
			}else {
				if (val == "") 
					val = strDefault;
				if (val == strDefault) 
					c = color2;
				else 
					c = color;
				$this.bind("focus", function(){
					var $this = $(this);
					if ($this.val() == strDefault) {
						$this.val("").css("color", color);
					}
				}).bind("blur", function(){
					var $this = $(this);
					if ($this.val() == "") {
						$this.val(strDefault).css("color", color2);
					}
				});			
			    return this.each(function(){
					$(this).val(val).css("color", c);
				});
			}
		},
		inputTips: function(expr, beforeFun){
			var $tipsArea = $(expr);
			return this.each(function(){
				var $this = $(this), open;
				if($this.is("input") || $this.is("textarea")){
					$this.bind("focus.inputTips", function(){
						if($.isFunction(beforeFun))
							open = beforeFun.apply($this, [$tipsArea]);
						if(open !== false)
							$tipsArea.stop(true).toggle(true).animate({
								opacity: 1							
							});
					}).bind("blur.inputTips", function(){
						$tipsArea.stop(true).animate({
							opacity: 0							
						}, function(){
							$tipsArea.toggle(false);
						});
					});
				}
			});
		},
		checkInputLength: function(){
			var $this = $(this);
			if($this.is("textarea") || $this.is("input")){				
				var args = arguments, type = "keyup", min, max, checkFun, chinese = true, timer = null;
				for(var i = 0; i < args.length; i++){
					if(args[i] instanceof Array){
						min = args[i][0];
						max = args[i][1];
					}else{
						switch(typeof args[i]){
							case "string":
								type = args[i];
								break;
							case "number":
								if(min === undefined){
									min = args[i];
								}else{
									max = args[i];
								}
								break;
							case "function":
								checkFun = args[i];
								break;
							case "boolean":
								chinese = args[i];
								break;
						}
					}
				}
				if(max === undefined){
					return;
				}
				chinese = chinese ? "a" : "aa";
				$this.bind(type, function(e){
					var _this = this;
					if (!timer) {
						timer = setTimeout(function(){							
							var val = $.trim($this.val()), len, pass, str;
							if (val) {
								val = val.replace("/[^\x00-\xff]/gi", chinese);
							}
							len = val.length;
							pass = (len >= min && (len <= max || max === 0));
							if (!pass) {
								str = "输入的文字不能" + (len >= min ? ("超过" + max) : ("小于" + min)) + "个!";
							}else{
								str = "您还可以输入 " + (max - len) + "个字。";
							}
							if (checkFun) 
								checkFun.call(_this, e, len, str, pass);
							timer = null;
						}, 50);
					}		
				});
			}
		}
	});
	$.checkLength = function( min, max, val, chinese){
		val = $.trim(val);
		chinese = chinese === undefined ? true : chinese;
		chinese = chinese ? "a" : "aa";
		if (val) {
			val = val.replace("/[^\x00-\xff]/gi", chinese);
		}
		var len = val.length;
		return (len >= min && (len <= max || max === 0));
	}
})(jQuery, window);

(function($, window){

// Tabs exchange
$.fn.tabs = function (opts, callBack) {
    var opts = opts;
    if(!opts) return;
    var evt = opts["evt"] ? opts["evt"] : opts["type"] ? opts["type"] : "click";
    var className = opts["className"] ? opts["className"] : "current";
    var target = opts["target"]? opts["target"] : null;
    var index = opts["index"]? opts["index"] : 0;
    
    $(this).eq(index).addClass(className);
	if (target) {
		target.toggle(false);
		target.eq(index).toggle(true);
	}
    $(this).each(function (i) {
        $(this).unbind().bind(evt, function () {
            $(this).addClass(className).siblings().removeClass(className);
            $(target).toggle(false).eq(i).toggle(true);
            if (callBack && jQuery.isFunction(callBack)) 
				callBack.call(this ,i);
        })
    })
}

// select all input[ type = checkbox ]
$.fn.selectAll = function (opts, context) {
	var name = (opts instanceof $ || opts.nodeType === 1) ? null : 
					(typeof opts == "object" && opts.checkName) ? opts.checkName : opts.toString(),
		allCheackbox = name ? $( "input[name=" + name + "]", context ? context : document ) : $(opts),
		checkbox = $(this).is("input[type=checkbox]"),
		checked,
		$this = (this);
	if(allCheackbox.length == 0)return this;
	allCheackbox.click(function(){
		var $item = $(this), checked = !$item.data("checked");
		if (!checked && $this.data("checked")) {
			if(checkbox)
				$this.attr("checked", checked);
			$this.data("checked", checked)
		}
		$item.data("checked", checked);
	});
	return this.each(function(){
		$(this).click(function(){
			checked = checkbox ? $(this).is(":checked") : !$(this).data("checked");
			allCheackbox.filter("[type=checkbox]").attr("checked", checked)
			allCheackbox.data("checked", checked);
			$this.data("checked", checked);
		});
	})
}
// Document cookies
$.cookie = new Object();
$.cookie.set = function (CookieName, CookieValue, nDays, Domain) {

    if (CookieName === null || CookieName === "" || CookieName === undefined) return "";
    var today = new Date();
    var expire = new Date();
    if (nDays == null || nDays == 0) {
        nDays = 1;
    }
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    var strDomain = "";
    if(Domain) strDomain = "domain=" + Domain + ";";
    document.cookie = CookieName + "=" + escape(CookieValue) + ";expires=" + expire.toGMTString() + ";path=/;" + strDomain;
}
$.cookie.get = function(CookieName){
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; "); 
    for (var i = 0; i < arrCookie.length; i++) { 
        var arr = arrCookie[i].split("="); 
        if(arr.length >= 1)
        {
            if (unescape(arr[0].replace(/(^\s*)|(\s*$)/g, "")) == CookieName)
            {
                if(arr.length >= 2)
                {
                    try
                    {
                        return unescape(arr[1]);
                    }
                    catch(ex)
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
        }
    }
    return "";
}
$.cookie.del = function(CookieName){
    var date=new Date();
    date.setTime(date.getTime()-3600000);
    document.cookie=CookieName+"=v; expire="+date.toGMTString();
}

// tips
$.tips = function (text,evt) {
    if(!text) return;
    var customTips = $("#CUSTOM_TIPS");
    if(customTips.length == 0){
        customTips = $("<div style='border:1px solid #000; background:yellow; padding:2px 4px; position:absolute; font-size:12px' />").html(text);
    }
    var x = evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    var y = evt.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    customTips.css({"left": x, "top": y + 21 }).prependTo(document.body).show();
    var auto = setTimeout(function(){
        if(customTips.get(0).style.display != "none"){
            customTips.hide();
        }
        clearTimeout(auto);
    },5000)
    $(document).click(function(e){
        if(e.target != customTips.get(0)){
            customTips.hide();
            clearTimeout(auto);
        }
    })
    
    evt.stopPropagation();
}
})(jQuery, window);
// copy
function CopyText(text, notdebug) {
	var copy = true
	if (window.clipboardData) {
		window.clipboardData.clearData();
		window.clipboardData.setData("Text", text);
	}else if (!notdebug) {
		alert("非IE浏览器请用Ctrl+c手动复制链接");
		copy = false;			
	}
	return copy;
};

// addfavorite
function addfavorite(url,title) {
    var url = url || top.location.href;
    var title = title || top.document.title;
    if (document.all) {
        window.external.addFavorite(url,title); } 
    else if (window.sidebar)  { 
        window.sidebar.addPanel(title, url, "");  
    }
}

function json_encode (feed){
	var r = [], s = "";
	if(feed === undefined || feed === null || feed === "")return "\"\"";
	if(feed instanceof Array){
		r.push("[");
		for(var i = 0; i < feed.length; i++){
			r.push(s);
			r.push(arguments.callee(feed[i]));
			s = ",";
		}
		r.push("]");
	}else if(typeof feed == "object"){
		r.push("{");
		for(var k in feed){
			r.push(s);
			r.push("\"");
			r.push(k);
			r.push("\":");
			r.push(arguments.callee(feed[k]));
			s = ",";
		}
		r.push("}");
	}else if(!isNaN(feed) && (!(/^0/.test(feed)) || feed === 0)){
		r.push(feed);
	}else {
		feed = feed.toString().replace("\\", "\\\\");
		feed = feed.replace("\"", "\\\"");
		r.push("\"" + feed + "\"");
	}
	return r.join("");
}
function json_decode(str){
	try{		
		return jQuery.parseJSON(str);
	}catch(e){
		return null;
	}
}
function htmlEncode(html){
	return html.replace(/\</g, "&lt;").replace(/\>/g,"&gt;");
}

jQuery.extend({
	//根据网址在回调函数中返回expr中和网址匹配的a标签
	currentByHref:function(expr, href, fun){
		var elems = $(expr), h, c, p = -1, e = null;
		elems = elems.is("a") ? elems : $("a", elems);
		if(elems.length == 0)return;
		
		var filter = false;
		if(typeof href == "string"){
			h = href;
			filter = true;
		}else{
			h = location.href;
		}
		
		h = h.toLowerCase();
		
		if($.isFunction(href)){
			c = href;
		}else{
			c = fun;
		}
		elems.each(function(){
			var _p;
			if(filter)
				_p = $(this).attr("href").toLowerCase().indexOf(h);
			else
				_p = h.indexOf($(this).attr("href").toLowerCase());		
			if(_p != -1 && (_p <= p || p == -1)){
				e = $(this);
				p = _p;
				if($(this).attr("href").toLowerCase() == h){
					p = -2
				}
			}
		});
		if (e) {			
			$.isFunction(c) ? c.call(e, e) : e.addClass("current");
		}
	}
});
(function(window){
	//localhost.search 读写
	var gets = null;
	window.$_GET = function (name, notLowerCase, decodeType){
		if (!gets) {
			var ls = location.search, _pos, paraName, paraValue;
			gets = {};
			ls = ls.substr(1);
			ls = ls.split("&");
			for (var i = 0; i < ls.length; i++) {
				_pos = ls[i].indexOf('=');
				if (_pos == -1) 
					continue;
				paraName = $.trim(ls[i].substring(0, _pos)).toLowerCase();
				paraValue = $.trim(ls[i].substring(_pos + 1)).replace(/\+/g, " ");
				gets[paraName] = paraValue;
			}
		}
		if(!isNaN(notLowerCase)){
			decodeType = notLowerCase;
			notLowerCase = false;
		}else{
			decodeType = decodeType ? parseInt(decodeType) : 0;			
		}
		var n = name.toLowerCase(), decodeFun;	
		switch(decodeType){
			case 3:
				decodeFun = decodeURI;
				break;
			case 2:
				decodeFun = decodeURIComponent;
				break;
			case 1:
				decodeFun = unescape;
				break;				
			default:
				decodeFun = function(text){return text;}
				break;
		}
		if (gets[n]) {
			var r = notLowerCase ? gets[n] : gets[n].toLowerCase();
			try{
				return decodeFun(r);
			}catch(e){
				return r;
			}			
		}
		else 
			return null;
	}
	window.setHash = function( val, href, go ){
		if(href === undefined || typeof href == "boolean"){			
			go = href === undefined ? true : href;
			href = location.href;
		}else{
			href = href || location.href;
			go = go === undefined ? true : href;
		}
		var thisPage = href == location.href, newhref = "";	
		if(go && thisPage){
			location.hash = val;
		}else{
			var newhref = href.replace(/^(.+?)(#.*)?$/i, "$1" + "#" + val);
			if(go)
				location.href = newhref;
			else
				return newhref;
		}
	}	
	window.setSearch = function( name, val, go, encodeType){
	    var goSearch, obj = {}, ls, r1, r2, arr = [], c = "", pn, href, encodeFun, hash = "", hashPos = -1;
		if(typeof(name) == "object"){
			obj = name;
			goSearch = val;
		}else {
			obj[name] = val;
			goSearch = go
		}		
		if(goSearch === undefined || goSearch === true || !isNaN(goSearch)){
			href = location.href;
			encodeType = !isNaN(goSearch) ? goSearch : 0;
			goSearch = true;
		}else {
			href = goSearch || location.href;
			encodeType = encodeType ? parseInt(encodeType) : 0;
			goSearch = false;
		}		
		switch(encodeType){
			case 3:
				encodeFun = encodeURI;
				break;
			case 2:
				encodeFun = encodeURIComponent;
				break;
			case 1:
				encodeFun = escape;
				break;				
			default:
				encodeFun = function(text){return text;}
				break;
		}
		hashPos = href.indexOf("#");
		if (hashPos > -1) {
			hash = href.substr(hashPos);
			href = href.substr(0, hashPos);
		}
		if(/^([^?]+)(\?(?:.*))?$/i.test(href)){
			pn = RegExp.$1;
			ls = RegExp.$2;		
		    if(!ls){
		        arr.push("?");      
		        for(var k in obj){
					if (obj[k] === null || obj[k] === undefined)
						continue;
					arr.push(c);
					arr.push(k);
					arr.push("=");
					arr.push(encodeFun(obj[k]));
					c = "&";
		        }
		        ls = arr.join("");
		    }else{
		        for(var k in obj){		
					if (obj[k] === null || obj[k] === undefined)
						continue;
		            r1 = new RegExp("(?:&|\\?)"+ k + "=","i");
		            if(r1.test(ls)){
		                r2 = new RegExp("^(\\?(?:.*&)*" + k + "=).*?(&.*)*$","i");
		                ls = ls.replace(r2, "$1" + encodeFun(obj[k]) + "$2");			
		            }else{
		                ls += "&" + k + "=" + encodeFun(obj[k]);
		            }
		        }
		    }
			if(goSearch === true)
		    	location.search = ls;
			else
				return pn + ls + hash;
		}else{
			return goSearch;
		}
	}
})(window);
(function(){
	var len = 0, timer = null;
	$.extend({		
		ajaxLoading:function(expr){
			var e = $(expr ? expr : "<div class=\"ajaxloading\">数据加载中,请稍候...</div>").toggle(false);
			e.css({
				"background": "url(http://img.tgimg.cn/common/loading.gif) no-repeat 0 0",
				"top": "0px",
				"left":"40%",
				"height":"16px",
				"line-height":"16px",
				"position":"absolute",
				"padding-left":"16px"
			});
			$(function(){
				$("body").append(e);				
			});
			$(document).bind("scroll.ajaxloading", function(){
				if(!timer)
					timer = setTimeout(function(){
						e.css({top: $(this).scrollTop() + "px"});
						timer = null;					
					},10);
			});
			e.ajaxStart(function(){
				len++;
				e.toggle(true);
			}).ajaxStop(function(){
				len--;
				if(len <= 0){
					len = 0;
					e.toggle(false);
				}
			});
		}
	});
})();

(function($){
	$.extend({
		postForm: function( action, data, target, enctype, accept, acceptCharset ){
			$.sendForm( action, data, "post", target, enctype, accept, acceptCharset );
		},
		getForm: function( action, data, target, enctype, accept, acceptCharset ){
			$.sendForm( action, data, "get", target, enctype, accept, acceptCharset );
		},
		sendForm: function( action, data, method, target, enctype, accept, acceptCharset ){
			if(typeof action == "string"){
				action = getOptions.apply(this, arguments);
			}
			var form = createForm(action, data);
			form.appendTo("body");
			form.submit();
			//form.remove();
		},
		ajaxForm: function( form, data, success){
			if(typeof form == "string" && typeof data == "object"){
				form = createForm(getOptions(form), data);
			}else if( $.isFunction(data) ){
				form = $(form);
				success = data;
			}else{
				return;
			}
			form.attr("target", "ajaxIframe");
			form.attr("enctype", "multipart/form-data");
			form.attr("method", "post");
			var iframe = $("#ajaxIframe").unbind("load");
			if(iframe.length == 0){
				iframe = $("<iframe scrolling='no' frameborder='0' id='ajaxIframe' name='ajaxIframe' />").toggle(false);
			}
			$("body").append(iframe);
			form.submit();
			iframe.bind("load", function(event){
				var target = event.target; 
				var	doc = (target.contentWindow || target.contentDocument).document,
					text = doc.body ? doc.body.innerHTML : null,
					xml = doc.XMLDocument || doc;
				$.isFunction(success) && success(text, xml);
			});
		}
	});
	function getOptions(action, data, method, target, enctype, accept, acceptCharset){
		return {
			action: action,
			method: method || "post",
			target: target,
			enctype: enctype || "application/x-www-form-urlencoded",
			accept: accept,
			"accept-charset": acceptCharset
		};
	}
	function createForm(options, data){
		$("#ajaxFrom").remove();
		var f = $("<form id='ajaxFrom'/>").toggle(false).attr(options), input = $("<input type='hidden'/>");
		if(data instanceof jQuery)
			f.append(data.clone());
		else
			for(var n in data){
				f.append(input.clone().attr("name", n).val(data[n] ? data[n] : ""));
			}
		return f;
	}
})(jQuery);

//Event 只用于继承

var Event = function(){
 	if(this instanceof Event){
        this._handle = {};
    }else{
        return new Event();
    }
};
Event.prototype.bind = function( type, data, handle ){
	var namespace = "";
	if($.isFunction(data)){
		handle = data;
		data = undefined;
	}
	if( type.indexOf(".") > -1){
		namespace = type.split(".");
		type = namespace.shift();
		namespace = namespace.join(".");
	}
	if(!this._handle[ type ]){
		this._handle[ type ] = [];
	}
	if(!$.isFunction(handle)){
		handle = function(){};
	}
	this._handle[ type ].push({
		namespace: namespace,
		data: data,
		handle: handle
	});
};
Event.prototype.trigger = function( type, datas ){
	var namespace = "", events;
	if( type.indexOf(".") > -1){
		namespace = type.split(".");
		type = namespace.shift();
		namespace = namespace.join(".");
	}
	if(!(datas instanceof Array)){
		datas = datas ? [datas] : [];
	}
	if( type )
		events = this._handle[ type ] || [];
	else {
		if(!namespace)return;
		events = [];
		for(var n in this._handle){
			events = events.concat(this._handle[n]);
		}
	}
	for(var i = 0; i < events.length; i++){
		if (!namespace || events[i].namespace === namespace) {
			var event = {
				target: this,
				namespace: events[i].namespace,
				type: type,
				data: events[i].data
			}
			events[i].handle.apply(this, [event].concat(datas));
		}
	}
};
Event.prototype.unbind = function( type, handle ){
	var namespace = "";
	if( type && type.indexOf(".") > -1){
		namespace = type.split(".");
		type = namespace.shift();
		namespace = namespace.join(".");
	}
	if (type) {
		this._unbind( this._handle[type] || [], namespace, handle);
	}else {
		for (var n in this._handle) {
			this._unbind(this._handle[n], namespace, handle);
		}
	}
};
Event.prototype._unbind = function( events, namespace, handle){
	for (var i = events.length - 1; i >= 0; i--) {
		if(!namespace || events[i].namespace === namespace)
			if(!handle || handle === events[i].handle || handle.toString() === events[i].handle.toString()){
				events.splice(i, 1);
			}
	}
};

$.extend({
	TG:{
		status:{}, //全局变量，用于保存用户状态
		statusEvent: new Event(),
		setStatus: function( name, val ){
			if(val === undefined){
				return;
			}
			if (typeof name == "string") {
				$.TG.status[name] = val;
				$.TG.statusEvent.trigger("set." + name, name);
			}else if(typeof name == "object"){
				var _this = $.TG.setStatus;
				for(var n in name){
					_this( n, name[n] );
				}
			}
		},
		getStatus: function( name ){
			return $.TG.status[name];
		},
		bindStatus: function( name, fun, run ){
			if(name.indexOf(" ") > -1){
				name = name.split(" ");
				for(var i = 0; i < name.length; i++ ){
					if(name[i])
						$.TG.bindStatus(name[i], fun, run);
				}
				return;
			}
			var _fun = function(event, name){
				if($.isFunction(fun)){
					var val = $.TG.getStatus(name);
					fun.call(val, val);
				}
			};
			if(run && $.isFunction(fun)){
				var val = $.TG.getStatus(name);
				fun.call(val, val);
			}
			$.TG.statusEvent.bind("set." + name, _fun);
			
		},
		
		//关闭窗口事件
		_beforeUnloadFn: [],
		bindBeforeUnload: function( fn ){
			if($.isFunction(fn)){
				var a = $.TG._beforeUnloadFn;
				for(var i = a.length - 1; i >= 0; i--){
					if(fn == a[i] || fn.toString() == a[i].toString()){
						break;
					}
				}
				if(i === -1){
					a.push(fn);
				}
			}
		},
		unbindBeforeUnload: function( fn ){
			if($.isFunction(fn)){
				var a = $.TG._beforeUnloadFn;
				for(var i = a.length - 1; i >= 0; i--){
					if(fn == a[i] || fn.toString() == a[i].toString()){
						a.splice(i,1);
					}
				}
			}else if(!fn){
				$.TG._beforeUnloadFn = [];
			}
		},
		assign: function( expr, data, decode){	
			if(!(data instanceof Array)){
				data = [data];
			}
			if(decode === undefined){
				decode = true;
			}
			var $this = $(expr), t = $this.data("tgassignTemplate"), s = "", re = {};
			if(!t){
				t = $this.html();
				$this.data("tgassignTemplate", t);
				$this.empty();
			}
			for(var i = 0; i < data.length; i++){
				if(typeof data[i] == "object"){
					var _s = t;
					for(var n in data[i]){
						if(!re[n])
							re[n] = new RegExp("#" + n + "#", "g");
						_s = _s.replace(re[n], decode ? decodeURIComponent(data[i][n]) : data[i][n]);
					}
					s += _s;
				}
			}
			$this.html(s);
			$this.find("img").each(function(){
				var $this = $(this),
					_src = $this.attr("_src");
					if(_src)
						$this.attr("src", _src).removeAttr("_src");
			});
			return ;
		}
	}
});

window.onbeforeunload = function(e){
	var e = e || window.event;
	try {
		var a = $.TG._beforeUnloadFn, notclose = false, str;
		for (var i = 0; i < a.length; i++) {
			if ((str = a[i]())) {
				notclose = true;
				break;
			}
		}
		if (notclose) {
			str = typeof(str) == "string" ? str : "当前操作未保存，如果你此时离开，所做操作信息将全部丢失，是否离开?";
			return str;
		}
	}catch(e){}
}; 

//输入验证
(function($){
	var checkFunObj = {},
		checkReg = [];
	checkReg.push({name: "mobile", reg: [/^0?1\d{10}$/]});
	checkReg.push({name: "email", reg: [/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i]});
	checkReg.push({name: "url", reg: [/^(http(s)?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/]});
	checkReg.push({name: "tel", reg: [/^[\d-()]{8,20}$/]});
	checkReg.push({name: "qq", reg: [/^\d{5,16}$/]});
	function _test(){
		var len = arguments.length - 1, val = $.trim(arguments[len]), re = true;
		for(var i = 0; i < len; i++){
			re = arguments[i].test(val);
			if(!re){
				break;
			}
		}
		return re;
	}
	for(var i = 0; i < checkReg.length; i++){
		checkFunObj[checkReg[i].name] = (function(){
			var reg = checkReg[i].reg;
			return function( val ){
				return _test.apply(this, reg.concat([val]));
			};
		})();
	}
	$.extend($.TG, {
		check: checkFunObj
	});
})(jQuery);
//时间格式转换
(function(window, $){
	$.extend($.TG, {
		timeFormat: function(date, format){
			if(typeof date == "string"){
				date = new Date(date);
			}else if( !(date instanceof Date) ){
				return "";
			}
			if(!format || typeof format != "string"){
				format = "yyyy-mm-dd"; 
			}			
			var r = format, 
				fullYear = date.getFullYear(), 
				year = (fullYear + "").substr(2),
				month = date.getMonth() + 1,
				fullMonth = month > 9 ? month : "0" + month,
				d = date.getDate(),
				fullD = /^\d{1}$/.test(d) ? "0" + d : d,
				hours = date.getHours(),
				fullHours = hours > 9 ? hours : "0" + hours,
				minutes = date.getMinutes(),
				fullMinutes = minutes > 9 ? minutes : "0" + minutes,
				seconds = date.getSeconds(),
				fullSeconds = seconds > 9 ? seconds : "0" + seconds;
			r = r.replace(/y{4}/gi, fullYear);
			r = r.replace(/y{2}/gi, year);
			r = r.replace(/m{2}/gi, fullMonth);
			r = r.replace(/m/gi, month);
			r = r.replace(/d{2}/gi, fullD);
			r = r.replace(/d/gi, d);
			r = r.replace(/H/g, fullHours);
			r = r.replace(/h/g, hours);
			r = r.replace(/I/g, fullMinutes);
			r = r.replace(/i/g, minutes);
			r = r.replace(/S/g, fullSeconds);
			r = r.replace(/s/g, seconds);
			return r;
		}
	})
})(window, jQuery);

//form修改后关闭窗口提示
(function(window, $){
	var forms = [];
	
	$.TG.bindBeforeUnload(function(){
		var bConfirm = false;
		for(var i = 0; i < forms.length; i++ ){
			if(forms[i].val != getInputValString(forms[i].form, forms[i].except)){
				bConfirm = true;
				break;
			}
		}
		if (bConfirm) {
			return true;
		}
	});
	
	$.extend({
		updateRemind: function(form, opts){
			if (form) {
				var $form = $(form), except = opts.except, update = opts.update;				
				$form.each(function(){
					var $this = $(this), _this = $this.get(0);
					if ($this.is("form")) {
						if(update){
							for(var i = 0; i < forms.length; i++){
								if(forms[i]._form == _this){
									forms[i].except = except;
									forms[i].val = getInputValString($this, except);
								}
							}
							if(i == forms.length){
								update = false;
							}
						}
						if(!update){						
							forms.push({
								_form: _this,
								form: $this,
								except: except,
								val: getInputValString($this, except)
							});
						}
					}
				});
			}else{
				for(var i = 0; i < forms.length; i++){
					forms[i].val = getInputValString(forms[i].form, forms[i].except);
				}
			}
		}
	});
	
	$.extend( $.fn, {
		updateRemind: function( opts ){
			var except, update;
			switch(typeof opts){
				case "string":
					except = opts;
					update = false;
					break;
				case "boolean":
					except = null;
					update = opts;
					break;
				case "object":
				default:					
					except = opts && opts.except ? opts.except : null;
					update = opts && opts.update ? opts.update : false;
					break;
					 					
			}
			$.updateRemind(this, {
				except: except,
				update: update
			});
			return this;
		}
	});
	
	function getInputValString( $form, except ){
		var select = $form.find("select"),
			_input = $form.find("input"),
			checkbox = _input.filter("[type=checkbox]:checked"),
			radio = _input.filter("[type=radio]:checked"),
			text = _input.filter("[type=text]"),
			password = _input.filter("[type=password]"),
			input = $(),
			valObj = {},
			valString = [];
		$.merge(input, select);
		$.merge(input, checkbox);
		$.merge(input, radio);
		$.merge(input, text);
		$.merge(input, password);
		(except ? input.not(except) : input).each(function(){
			var $this = $(this), name = $this.attr("name");
			if(!valObj[name])
				valObj[name] = [];
			valObj[name].push($this.val());
		});
		for(var n in valObj){
			valString.push(n);
			valString.push("=");
			valString.push(valObj[n].join(","));
			valString.push("&");
		}
		return valString.join("");
	}
})(window, jQuery);

//用户操作
(function(window, $){
	var setting = {
		username: "[name=username]",
		usernameDefaultValue: "手机号/邮箱/会员名",
		password: "[name=password]",
		beforeLogin: function(){},
		code: "[name=code]",
		submit: "[type=submit]",
		remember: "[name=remember]",
		forgetpwd: "<a href=\"http://user.tgnet.cn/forgetpwd.aspx\" target=\"_blank\">找回登录密码</a>",
		loginurl: "/System/AjaxService.aspx",
		logouturl: "/System/AjaxService.aspx",
		loginop: "login",
		logoutop : "logout",
		loginError:function(msg, data){
			var text = data && data.Msg ? data.Msg : (msg || "");
			alert(text);
		},
		loginsuccess:function(data){
			return true; //执行_loginsuccess
		},
		_loginsuccess:function(data){
			location.reload(true);
			return false;
		},
		logoutsuccess:function(data){
			if(data.State === 0){
				location.reload(true);
				return false;
			}else{
				alert(data.Msg);
			}
		},
		validate: null
	};
	//没有validate的情况下使用
	function showError(s, msg){
		if(!s.validate && s.errorArea)
			s.errorArea.toggle(true).html(msg);
	}
	function hideError(s){
		if(!s.validate && s.errorArea)
			s.errorArea.toggle(false);
	}
	function login(s, setting, u, p, c){
		var uVal = $.trim(u.val()), msg , element;
		if (!uVal || uVal == setting.usernameDefaultValue) {
			msg = "请输入帐号";
			element = u;
		}
		else 
			if (!$.trim(p.val())) {
				msg = "请输入密码";
				element = p;
			}
			else 
				if (c && c.length && !$.trim(c.val())) {
					msg = "请输入验证码";
					element = c;
				}
				else {
					hideError(setting);
					s.sendAjax(setting.loginop);
					return;
				}
		showError(setting, msg);
		if(setting.loginError){
			setting.loginError(msg);
		}
		element.focus();
	}
	$.extend($.TG, {
		user: {
			bindLogin: function( context /*, options */){
				var options = arguments[1], s = {}, errorCount = 0;
				if(options){
					$.extend(true, s, setting, options);
				}else{
					$.extend(true, s, setting);
				}
				context = $(context);
				if(context.length){
					 context.each(function(){
					 	var $this = $(this), form, u, p , c, b, r;
						form = $this.is("form") ? $this : (form = $this.find("form")).length ? form : $this;
						u = $(s.username, form).enter(function(){p.focus();}).keywords(s.usernameDefaultValue);
						p = $(s.password, form).enter(function(){ c && c.length ? c.focus() : b.triggerHandler("click"); });
						b = $(s.submit, form);
						c = $(s.code, form).enter(function(){
							b.triggerHandler("click");
						});
						r = $(s.remember, form).enter(function(){
							b.triggerHandler("click");
						});
						if(s.errorArea){
							s.errorArea = $(s.errorArea);
						}
						if (u.length && p.length && b.length) {
							if ($.validator && s.validate) {
								b.enter("enter", function(){
									$this.triggerHandler("click");
								});
								b.bind("click", function(){
									form.submit();
								});
								s.validate.submitHandler = function(){
									login(b, s, u, p, c);
								}
								form.validate(s.validate);						
							}
							else {
								b.bind("click enter", function(){
									login(b, s, u, p, c);
								});
							}
							b.addAjax(s.loginop, {
								beforeSend: s.beforeLogin,
							 	url: s.loginurl,
							 	success: function(data){
									if (data.State === 0) {
										var sr = s.loginsuccess(data, u, p, c);
										if (sr === undefined || sr) {
											s._loginsuccess();
										}
										return false;
									}
									else {
										$.TG.setStatus("userLoginErrorState", data.State);
										errorCount++;
										if (data.Msg) {
											var msg = data.Msg;
											if (errorCount > 0) {
												msg += s.forgetpwd;
											}
											showError(s, msg);
										}
										if (s.loginError) 
											return s.loginError(msg, data);
									}
								},
								error: function(){
									showError(s, "网络错误,请稍后重试!");
									if (s.loginError) 
										s.loginError("网络错误,请稍后重试!");
								}
						 	}, false, true, [u, p, c, r]);
						}
					 });
				}
			},
			bindLogout: function( btns/*, options */ ){
				var options = arguments[1], s = {}, btns = $(btns);
				if(typeof options == "object"){
					$.extend(true, s, setting, options);
				}else if($.isFunction(options)){
					$.extend(true, s, setting, {logoutsuccess:options});
				}else{					
					$.extend(true, s, setting);
				}
				btns.addAjax(s.logoutop, {
					success: s.logoutsuccess
				}, false, "退出中..").click(function(){
					btns.sendAjax(s.logoutop);
				});
			}
		}
	});
})(window, jQuery);
(function(){
	GoogleMap = function(a, address){
		var strUrl = 'http://ditu.google.cn/maps?f=q&hl=zh-CN&q=' + address;
	    a.target = '_blank';
	    a.href = strUrl;
	}
})(jQuery);
