var $ = jQuery;//重新申明$变量

$.browser.msie6 = $.browser.msie && ($.browser.version == 6.0)
$.browser.msie7 = $.browser.msie && ($.browser.version == 7.0)
$.browser.chrome = navigator.userAgent.indexOf("Chrome") != -1
$.browser.gecko = navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("KHTML") == -1

if (typeof argumentsToArray == "undefined"){
	function argumentsToArray(args){
		var arr = [];
		for (var i=0, len=args.length; i<len; ++i){
			arr.push(args[i]);
		}
		return arr;
	}
}

if (typeof Function.prototype.bindContext == "undefined"){
	Function.prototype.bindContext = function(){
		var method = this, args=argumentsToArray(arguments),scope=args.shift();
		return function(){
			return method.apply(scope, args.concat(argumentsToArray(arguments)));
		}
	}
}

if (!String.prototype.ltrim){
	String.prototype.ltrim = function(){
		return this.replace(/^\s*/, "");
	}
}

if (!String.prototype.rtrim){
	String.prototype.rtrim = function(){
		return this.replace(/\s*$/, "");
	}
}

if (!String.prototype.trim){
	String.prototype.trim = function(){
		return this.ltrim().rtrim();
	}
}

if(!String.prototype.removeAllWhitespace){
	String.prototype.removeAllWhitespace=function(){
		return this.replace("/s+/g","")
	}
}

/**
 * 
 * @param {String} val
 * @param {Object} array
 * @param {Boolean} deep
 * @param {Object} func
 */
function in_array(val, array, deep, func){
	if (array == null){return -1}
	if (deep){
		for (var i = 0, len = array.length; i < len; ++i){
			if (func(array[i]) == val){
				return i
			}
		}
		return -1
	}else{
		return $.inArray(val, array)
	}
}

/**
 * 
 * @param {Array} array
 * @param {Function} funcname
 * @param {Mixed} userdata
 */
function array_walk(array, funcname, userdata){
	var callval;
	for (var i =0; i < array.length; ++i){
		callval = funcname(array[i], userdata, array, i);
		if (callval != null){
			array[i] = callval;
		}
	}
}

function strcmp(str1, str2){
	if (str1 == str2){
		return 0;
	}
	if (str1 == null){return -1;}
	if (str2 == null){return 1;}
	
	var fstr1 = parseFloat(str1), fstr2 = parseFloat(str2);
	if (!isNaN(fstr1) && !isNaN(fstr2) && fstr1 != fstr2){
		return fstr1 < fstr2 ? -1 : 1;
	}
	return str1 < str2 ? -1 : 1;
}

function ns(lnk){
	if ($.browser.msie){
		lnk.bind("focus", function(){
			this.blur()
		});
		lnk[0].onmousedown = lnk[0].onselectstart = lnk[0].ondragstart = function(){return false;}
	}
}

function createSeccode(){
	var $code = $("<a/>").attr({"href" : "javascript:;", "title" : "看不清？点击更换一张"}).addClass("captcha");
	var rand = Math.random();
	if ($.browser.msie6){
		var img = $("<img />").attr("src", "/seccode.php?update="+rand);
		img.appendTo($code);
		$code.bind("click", function(){
			$(this).empty();
			var img = $("<img />").attr("src", "/seccode.php?update="+Math.random());
			img.appendTo($code);
			this.blur()
		})
	}else{
		$code.css({
			"background-image" : "url(/seccode.php?update="+rand+")"
		});
		$code.bind("click", function() {
			$code.css({
				"background-image" : "url(/seccode.php?update="+Math.random()+")"
			});
        })
	}	
	return $code
}

function revealSeccode(){
	var $sec = $("#commentscecode");
	if ($sec.children().length < 1){
		var code = createSeccode();
		code.appendTo($sec);
		$parent = $sec.parent();
		$parent.css("display", "");
	}
}

//检测搜索
function checkSearchKeywords() {
	if (document.getElementById("keyword").value.length < 2) {
		alert(lang["search_content_short"]);
		document.getElementById("keyword").focus();
		document.getElementById("keyword").select();		
		return false;
	} else {
		return true;
	}
}

function validataForm(obj){
	var area = $("#comment-editbox");
	//首先检测area
	var bvalid = false, cvalid = false;
	if ($.trim(area.val()).length < 10){
		bvalid = false;
		alert("你的评论需要超过10个字符");
	}else if ($.trim(area.val()).length > 7500){
		bvalid = false;
		alert("你的评论超过7500个字符");
	}else{
		bvalid = true;
	}
	if (bvalid){
		if (obj.elements.captcha.value.length == 4){
			cvalid = true;
		}else{
			cvalid = false;
			alert("请重新输入验证码!");
			obj.elements.captcha.focus()
		}
	}
	return (bvalid && cvalid);
}

function validata(obj){
	var bvalid = false
	if ($.trim(obj.val()).length < 10){
		bvalid = false;
		alert("你的评论需要超过10个字符");
	}else if ($.trim(obj.val()).length > 7500){
		bvalid = false;
		alert("你的评论超过7500个字符");
	}else{
		bvalid = true;
	}
	return bvalid;
}

function getGets(){
	if (getGets.cache != null){
		return getGets.cache;
	}
	var cache = {};
	if (location.search){
		var info = decodeURIComponent(location.search.substr(1)).split("&");
		//分析参数
		for (var a=0, len = info.length; a < len; ++a){
			var isArgment = info[a].indexOf("=");
			var key, value;
			if (isArgment != -1){
				key = info[a].substr(0, isArgment);
				value = info[a].substr(isArgment + 1)
			}else{
				key = info[a];
				value = "";
			}
			cache[key] = value;
		}
	}	
	getGets.cache = cache;
	return cache;
}

function onAfterTyping(parent, func, time){
	var timer
	var _func = function(){
		if (timer){
			clearTimeout(timer);
			timer = null
		};
		timer = setTimeout(func, timer);
	}
	parent[0].onkeyup = _func;
}

function registerEvent(obj, e, func){
	if ($.browser.msie){
		obj.attachEvent("on"+e, func);
	}else{
		obj.addEventListener(e, func, false);
	}
}

function unregisterEvent(obj, e, func){
	if ($.browser.msie){
		obj.detachEvent("on"+e, func);
	}else{
		obj.removeEventListener(e, func, false);
	}
}

function stopProp(e){
	if (!e){
		e = event;
	}
	if ($.browser.msie){
		e.cancelBubble = true
	}else{
		e.stopPropagation();
	}
}

function ws_enableScroll(status){
	if (!status){
		registerEvent(document, "mousewheel", ws_enableScroll.func);
		registerEvent(window, "DOMMouseScroll", ws_enableScroll.func);
	}else{
		unregisterEvent(document, "mousewheel", ws_enableScroll.func);
		unregisterEvent(window, "DOMMouseScroll", ws_enableScroll.func);
	}
}

ws_enableScroll.func = function(e){
	if (e.stopPropagation){
		e.stopPropagation()
	}
	if (e.preventDefault){
		e.preventDefault();
	}
	e.returnValue = false;
	e.cancelBubble = true;
	return false;
}

function getInfoFromEvent(e){
	if (!e){
		if (typeof event != "undefined"){
			e = event
		}else{
			return null
		}
	}
	if (e.which){
		e._button = e.which;
	}else{
		e._button = e.button;
		if ($.browser.msie){
			if (e._button & 4){
				e._button = 2
			}else{
				if (e._button & 2){
					e._button = 3
				}
			}
		}else{
			e._button = e.button + 1;
		}
	}
	e._target = e.target ? e.target : e.srcElement;
	e._wheelDelta = e.wheelDelta ? e.wheelDelta : -e.detail;
	
	return e
}

var get_wowpatch = ["3.1.3", "3.2.0", "3.2.2", "3.3", "???"];
var ws_user = {
	uid : 0,
	username: ""
}

function getCursorPos(e){
	var x, y
	if (window.innerHeight){
		x = e.pageX
		y = e.pageY
	}else{
		x = e.clientX + $(window).scrollLeft()
		y = e.clientY + $(window).scrollTop()
	}
	return {x: x, y:y}
}

/**
 * 
 * @param {Element} target
 * @param {function} func
 */
function bindClickEvent(obj, func){
	var currentStatus = 0;
	function callFunc(status){
		if (currentStatus){
			if (currentStatus != status){
				return;
			}
		}else{
			currentStatus = status;
		};
		func(true)
	};
	obj.oncontextmenu = function(){//屏蔽右键显示
		callFunc(1);
		return false;
	}
	$(obj).mouseup(function(e){
		e = getInfoFromEvent(e)
		if (e._button == 3 || e.shiftKey || e.ctrlKey){
			callFunc(2)
		}else{
			if (e._button == 1){
				func(false)
			}
		}
		return false
	})
}

function JsonToArray(a,b, f){
	var e = [];
	for (var c in a){
		if(b[c]){
			e.push(c)
		}
	}
	return e.sort(function(c, d){
		if (!f){
			f = b
		}
		return f[c].localeCompare(f[d])
	});
}

$.extend({
	rtrim: function(str, p){//str 字符串, p 需要匹配的字符
		var len = str.length;
		while (--len>0 && str.charAt(len) == p){}
		str = str.substring(0, len + 1);
		if (str == p){
			str = "";
		}
		return str
	},
	sprintf: function(str){
		var arg
		for (arg=1, len=arguments.length; arg<len; ++arg){
			str = str.replace("$"+arg, arguments[arg])
		}
		return str;
	}
})

function createGlow(str, className){
	var $glow = $("#<span/>");
	for (var e=-1; e<=1; ++e){
		for (var c = -1; c<=1; ++c){
			var $head = $("#<div/>").css({
				"position": "absolute",
				"white-space": "nowrap",
				"left": e+"px",
				"top": c+"px"
			})
			if (e == 0 && c == 0){
				$head.css("zIndex", 4)
			}else{
				$head.css({
					"color": "black",
					"zIndex": 2
				});
			}
			$head.text(str)
			$head.appendTo($glow);
		}
	}
	$glow.css({
		"position": "relative"
	})
	$glow.addClass("glow"+(className != null ? " " + className: ""));
	var $gspan = $("<span/>");
	$gspan.css("visibility", "hidden");
	$gspan.text(str)
	$gspan.appendTo($glow);
	return $glow;
}

function getIngameLink(color, lik, name){
	prompt("复制下面的代码，并粘贴至游戏的聊天窗口：", '/script print("'+$.sprintf("WoWShell数据库：Shift-点击链接复制到聊天窗口$1;", "\\124c"+color+"\\124H"+lik+"\\124h["+name+']\\124h\\124r")'));
}

function getMoneyHtml(money){
	var html = "";
	if (money >= 10000){
		html += '<span class="moneygold">' + Math.floor(money / 10000) + "</span>";
		money %= 10000;
	}else if(money >= 100){
		html += '<span class="moneysilver">' + Math.floor(money / 100) + "</span>";
		money %= 100;
	}else if(money >= 1){
		html += '<span class="moneycopper">' + money + "</span>";
	}
	return html;
}

function setSelectedLink(lnk, key){
	if (!setSelectedLink.groups){
		setSelectedLink.groups = {};
	}
	var g = setSelectedLink.groups;
	if (g[key]){
		g[key].toggleClass("selected");
	}
	lnk.addClass("selected");
	g[key] = lnk
}

function convertRatingToPrecent(lvl, type, v){
	var baseRatingTable = {
		12 : 1.5,
        13 : 12,
        14 : 15,
        15 : 5,
        16 : 10,
        17 : 10,
        18 : 8,
        19 : 14,
        20 : 14,
        21 : 14,
        22 : 10,
        23 : 10,
        24 : 0,
        25 : 0,
        26 : 0,
        27 : 0,
        28 : 10,
        29 : 10,
        30 : 10,
        31 : 10,
        32 : 14,
        33 : 0,
        34 : 0,
        35 : 25,
        36 : 10,
        37 : 2.5,
        44 : 3.756097412109376
	}
	if (lvl < 0){
		lvl = 0
	}else{
		if (lvl > 80){
			lvl = 80;
		}
	}
	
	if ((type == 14 || type == 12 || type == 15) && lvl < 34){
		lvl = 34;
	}
	if (v < 0){ v = 0};
	var str;
	if (baseRatingTable[type] == null){
		str = 0;
	}else{
		var base;
		if (lvl > 70){
			base = (82 / 52) * Math.pow((131/63), ((lvl-70)/10));
		}else{
			if (lvl > 60){
				base = (82 / (262 - 3 * lvl))
			}else{
				if (lvl > 10){
					base = (lvl - 8) / 52;
				}else{
					base = 2 / 52
				}
			}
		}
		str = v / baseRatingTable[type] / base;
	}
	return str;
}

function setRatingLevel(that, lvl, type, v){
	var popframe = prompt($.sprintf("输入需要计算的人物等级($1 - $2)", 1, 80), lvl);
	if (popframe != null){
		popframe |= 0;
		if (popframe != lvl && popframe >= 1 && popframe<=80){
			lvl = popframe;
			var str = convertRatingToPrecent(lvl, type, v);
			str = Math.round(str * 100) / 100;
			if (type != 12 && type != 37 ){
				str += "%";
			}
			$(that).html($.sprintf("$1 @ $2", str, lvl));
			that.onclick = setRatingLevel.bindContext(0, that, lvl, type, v);
		}
	}
}

function setInnerHtml(target, str, node){
	tar = target[0];
	if (tar.nodeName.toLowerCase() == node){
		target.html(str)
	}
	for (var c = 0; c < target.children().length; ++c){
		setInnerHtml(target.children(":eq("+c+")"), str, node)
	}
}

//创建一个导航navigation
function init_Path(route){
	var path = mn_path, $navParent = $("#navigation"), subMenu = null, lastSpan, noSub;
	$navParent.empty();
	if (init_Path.lastIt) {
		init_Path.lastIt.checked = null
	};
	$navParent.addClass("navigation");
	
	for (var i = 0; i < route.length; ++i){
		var $lnk, $span, hasSub;
		for (var j = 0; j < path.length; ++j) {
			if (path[j][0] == route[i]) {
				hasSub = 1;
				path = path[j];
				path.checked = 1;
				break;
			}
		}
		if (!hasSub){
			noSub = 1;
			break;
		}		
		$lnk = $("<a />");
		$span = $("<span />");
		if (path[2]){
			$lnk.attr("href", path[2]);
		}else{
			$lnk.attr("href", "javascript:;");
			$lnk.css({
				"text_decoration": "none",
				"color": "white",
				"cursor": "default"
			});
		}
		if (i < route.length - 1 && path[3]){
			$span.addClass("menuarrow");
		}
		$lnk.text(path[4] == null ? path[1] : path[4]);
		if (i == 0){
			$lnk[0].menu = mn_path;
		}else{
			$lnk[0].menu = subMenu[3];
		}
		$lnk.mouseover(Menu.show);
		$lnk.mouseout(Menu.hide);
		$lnk.appendTo($span);
		$span.appendTo($navParent);
		lastSpan = $span;
		subMenu = path;
		path = path[3];
		if (!path){
			noSub = 1;
			break;
		}		
	}	
	if (lastSpan && noSub){
		lastSpan.removeClass();
	}else{
		if (subMenu && subMenu[3]){
			lastSpan.addClass("menuarrow");
			var $lnk, $span = $("<span/>");
			$lnk = $("<a/>").attr("href", "javascript:;").css({
				"text_decoration": "none",
				"color": "white",
				"font-size": "13px",
				"cursor": "default"
			}).text("...");
			$lnk[0].menu = subMenu[3];
			$lnk.mouseover(Menu.show);
			$lnk.mouseout(Menu.hide);
						
			$lnk.appendTo($span);
			$span.appendTo($navParent);
		}
	}
	
	var $clear = $("<div />").addClass("clear").appendTo($navParent);
	init_Path.lastIt = subMenu;
}

var RedButton = {
	create: function(str, enableStatus, func){
		var _lnk = $("<a/>").attr("href", "javascript:;").addClass("button-red"), _em = $("<em/>"), _b = $("<b/>"), _i = $("<i/>"), _caption = $("<span/>");
		_i.appendTo(_b);
		_b.appendTo(_em);
		_caption.appendTo(_em);
		_em.appendTo(_lnk);
		RedButton.setText(_lnk, str);
		RedButton.enable(_lnk, enableStatus);
		RedButton.setFunc(_lnk, func);
		return _lnk
	},
	setText:function(lnk, str){
		lnk.children(":first").children(":eq(0)").children(":first").text(str);//b>i
		lnk.children(":first").children(":eq(1)").text(str)//span
	},
	enable:function(lnk, status){
		var ls = lnk.attr("class");
		if (status || status == null) {
			ls = ls.replace("button-red-disabled", "");
		}else {
			if (ls.indexOf("button-red-disabled") == -1) {
				ls += " button-red-disabled";
			}
		}
		lnk.attr("class", ls);
	},
	setFunc:function(target, func){
		if (!func){
			func = function(){};
		}
		target.click(func)
	}
}

var Menu = {
	divs: [], iframes: [], selection:[],
	show: function(){
		//this: a element
		try{
			clearTimeout(Menu.timer);
			if (Menu.currentLink){
				Menu._show(this)
			}else{
				if (this.className.indexOf("open") == -1){
					this.className = " open";
				}
				Menu.timer = setTimeout(Menu._show.bindContext(0, this), 100);
			}
		}catch(e){}
	},
	_show:function(e){//e: a element
		if (Menu.currentLink != e){
			var $a = $(e);
			Menu._hide();
			Menu.selection = [-1];
			Menu.currentLink = e;
			//index, submenu, eX, eY + eHeight + 1, eHeight + 8, eWidth, eY, false
			Menu.showDepth(0, e.menu, $a.offset().left, $a.offset().top + $a.outerHeight() - 2, $a.outerHeight() + 8, $a.outerWidth(), $a.offset().top, false);
			if (e.className.indexOf("open") == -1){
				e.className += " open"
			}
		}else{
			Menu.truncate(0);
			Menu.clean(0);
		}
	},
	showAtCursor: function(ele, x, y){
		clearTimeout(Menu.timer);
		Menu._hide();
		Menu.selection = [-1];
		Menu.currentLink = null;
		if (!(x && y)){
			ele = getInfoFromEvent(ele);
			var pos = getCursorPos(ele);
			x = pos.x;
			y = pos.y;
		}
		if ($.browser.msie6){
			x -= 2;
			y -= 2;
		}
		Menu.showDepth(0, this.menu, x, y, 0, 0, 0, true);
	},
	hide:function(){
		try{
			clearTimeout(Menu.timer);
			if (Menu.currentLink){
				Menu.timer = setTimeout(Menu._hide, 333);
			}else{
				this.className = this.className.replace("open", "")
			}
		}catch(err){}
	},
	_hide:function(){
		for (var i=0, len = Menu.selection.length; i<len; ++i){
			Menu.divs[i].css({
				"display":"none",
				"visibility": "hidden"
			})
			if ($.browser.msie6){
				Menu.iframes[i].css("display", "none")
			}
		}
		Menu.selection = [];
		if (Menu.currentLink){
			Menu.currentLink.className = Menu.currentLink.className.replace("open", "");
		}
		Menu.currentLink = null;
	},
	sepOver:function(){
		var parent = this.parent;
		var parentId = parent[0].index
		Menu.truncate(parentId);
		Menu.clean(parentId);
		Menu.selection[parentId] = -1;
	},
	elemOver:function(){
		var parent = this.parent;
		var parentId = parent[0].index
		var index = this.index
		var key = this.key
		var hasSub = (this.firstChild.className == "menusub");
		Menu.truncate(parentId + hasSub);
		if (hasSub && key != Menu.selection[parentId]){
			var $a = $(this);
			Menu.selection[parentId + 1] = -1;
			Menu.showDepth(parentId+1, parent[0].menuArray[index][3], $a.offset().left, $a.offset().top -2, $a.outerHeight(), $a.outerWidth() - 3, 0 , false);
		}
		Menu.clean(parentId);
		Menu.selection[parentId] = key;
		if (this.className.length){
			this.className += " open";
		}else{
			this.className = "open";
		}
	},
	elemClick:function(func){
		Menu._hide();
		func();
	},
	divOver:function(){
		clearTimeout(Menu.timer);
	},
	divOut:function(){
		clearTimeout(Menu.timer);
		Menu.timer = setTimeout(Menu._hide, 333)
	},
	getIframe:function(index){
		var $iframe;
		if (Menu.iframes[index] == null){
			$iframe = $("<iframe />").attr({
				"src": "javascript:0;",
				"frameborder": "0"
			}).appendTo("#layers");
			Menu.iframes[index] = $iframe;
		}else{
			$iframe = Menu.iframes[index]
		}
		return $iframe;
	},
	getDiv:function(index, data){
		var $div, div;
		if (Menu.divs[index] == null){
			$div = $("<div />").addClass("menu").appendTo("#layers");
			Menu.divs[index] = $div;
		}else{
			$div = Menu.divs[index];
		}
		div = $div[0];
		div.index = index;
		div.menuArray = data;
		return $div
	},
	/**
	 * 创建目录层在layers中, 并且显示出来
	 * 
	 * @param {int} index 索引ID
	 * @param {Object} submenu 子层目录数据
	 * @param {int} divX 目录div层所显示的x轴位置
	 * @param {int} divY 目录div层所显示的y轴位置
	 * @param {int} gapHeight 间隔高度
	 * @param {int} gapWidth 间隔宽度
	 * @param {int} eY 父层Y轴位置
	 * @param {boolean} isShow 是否需要显示
	 */
	showDepth:function(index, submenu, divX, divY, gapHeight, gapWidth, eY, isShow){
		var ie6frame, $main = Menu.getDiv(index, submenu);
		//清除$main的子节点
		$main.empty();
		var $table = $("<table/>"), 
		$tbody = $("<tbody/>"), 
		$tr=$("<tr/>"),
		$td=$("<td/>"),
		$container = $("<div/>"), 
		$outter = $("<div/>");
		var max_shown = 999;
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var scrollX = $(window).scrollLeft();
		var scrollY = $(window).scrollTop();
		
		//控制目录显示长度
		if (gapHeight > 0 && (index> 0 || submenu.length > 20)){
			if ((25 + 1) * submenu.length > windowHeight - 25 - eY){
				for (var j = 2; j<4; ++j){
					if (gapHeight / j * submenu + 30 < windowHeight - eY){
						break;
					}
					max_shown = Math.floor(submenu.length / j);
				}
			}
		}		
		var t = 0, L = 0;//初始化两个递增数
		for (var i=0, len=submenu.length; i< len ; ++i){
			var data = submenu[i];
			if (data[0] == null){
				var $span = $("<span />").addClass("separator").text(data[1]);
				$span[0].parent = $main;
				$span.mouseover(Menu.sepOver);
				$span.appendTo($outter);
			}else{
				var $a = $("<a/>");
				$a[0].parent = $main;
				$a[0].key = L++;
				$a[0].index = i;
				if (data[2]){
					if (Menu.currentLink && Menu.currentLink.menuappend){
						if (data[2].indexOf(Menu.currentLink.menuappend) == -1){
							$a.attr("href") = data[2] + Menu.currentLink.menuappend;
						}else{
							$a.attr("href") = data[2];
						};
					}else{
						if (typeof data[2] == "function"){
							$a.attr("href", "javascript:;");
							$a.click(Menu.elemClick.bindContext(0, data[2]));
						}else{
							$a.attr("href", data[2])
						}
					}					
				}else{
					$a.attr("href", "javascript:;");
					$a.css("cursor", "default");
				}
				$a.mouseover(Menu.elemOver);
				var $outerspan = $("<span/>"),// |>层
				$innerSpan = $("<span/>");//check, icon,text 层
				if (data[3] != null){
					$outerspan.addClass("menusub");	
				};
				if (data.checked){
					$innerSpan.addClass("menucheck");	
				};
				if (data.newWindow){
					$a.attr("target", "_blank");
				}
				if (data.className){
					$innerSpan.addClass(data.className)	
				}
				if (data.tinyIcon){
					$innerSpan.css("background", "url(/images/icons/tiny/" + data.tinyIcon.toLowerCase() + ".jpg) left center no-repeat")
				}
				$innerSpan.text(data[1]).appendTo($outerspan);
				$outerspan.appendTo($a);
				$a.appendTo($outter);
			}			
			if (t++==max_shown){
				$container.mouseover(Menu.divOver);
				$container.mouseout(Menu.divOut);
				$outter.appendTo($container);
				if (!$.browser.msie6) {
					var $p = $("<p/>");
					$("<em />").appendTo($p);
					$("<var />").appendTo($p);
					$("<strong />").appendTo($p);
					$container.appendTo($p);
					$p.appendTo($td);
				}else{
					$container.appendTo($td);
				}
				$td.appendTo($tr);
				$td=$("<td/>");
				$p = $("<p/>");
				$container = $("<div/>");
				$outter = $("<div/>");
				t = 0;
			}
		}		
		$container.mouseover(Menu.divOver);
		$container.mouseout(Menu.divOut);
		$outter.appendTo($container);		
		if (!$.browser.msie6){
			if (max_shown != 999){
				var $p = $("<p/>");
				$("<em />").appendTo($p);
				$("<var />").appendTo($p);
				$("<strong />").appendTo($p);
				$container.appendTo($p);
				$p.appendTo($td);
			}else{
				$("<em />").appendTo($main);
				$("<var />").appendTo($main);
				$("<strong />").appendTo($main);
				$container.appendTo($td);
			}
		}else{
			$container.appendTo($td);
		}		
		$td.appendTo($tr);
		$tr.appendTo($tbody);
		$tbody.appendTo($table);
		$table.appendTo($main);		
		//定位
		$main.css({
			"top": "-2323px",
			"left": "-2323px",
			"display": ""	
		});
		var tblHeight = $table.height(), tblWidth = $table.width();
		var fixedtblh = true, fixedtblw = true;
		if (!$.browser.msie6){
			tblHeight += 6;
			tblWidth += 5;
		}
		if (divX + tblWidth > windowWidth + scrollX || submenu.rightAligned){
			fixedtblw = false;
		}
		if (fixedtblw){
			if (divX + gapWidth + tblWidth > windowWidth){
				divX = Math.max(0, divX - tblWidth);
			}else{
				if (index > 0){
					divX += gapWidth;
				}
			}
		}else{
			divX = divX + gapWidth - tblWidth;
			if ($.browser.msie){
				divX -= 3;
			}
		}
		if ((index>0 || isShow) && divY + tblHeight > windowHeight + scrollY){
			divY = Math.max(scrollY + 5, windowHeight+scrollY - tblHeight);
		}
		$main.css({
			"left": divX+"px",
			"top": divY+"px"
		});
		if ($.browser.msie6){
			ie6frame = Menu.getIframe(index);
			ie6frame.css({
				"left": divX+"px",
				"top": divY+"px",
				"width": tblWidth+"px",
				"height": tblHeight+"px",
				"display": "",
				"visibility": "visible"
			});
		}
		$main.css("visibility", "visible");
		if ($.browser.opera){
			$main.css({
				"display": "none",
				"display": ""
			})
		}
	},
	truncate:function(base){
		var i;
		while (Menu.selection.length - 1 > base){
			i = Menu.selection.length - 1;
			Menu.divs[i].css({
				"display": "none",
				"visibility": "hidden"
			});
			if ($.browser.msie6){
				Menu.iframes[i].css("display", "none")
			}
			Menu.selection.pop();
		}
	},
	clean:function(base){
		for (var i = base; i < Menu.selection.length; ++i){
			if (Menu.selection[i] > -1){
				var $ele = (Menu.divs[i]).find("a")[Menu.selection[i]];
				if ($ele.className.indexOf("sub") == -1){
					$ele.className = "sub";
				}else{
					$ele.className = "";
				}		
			}
			Menu.selection[i] = -1
		}
	},
	find: function(){
		
	},
	append: function(data, uri){
		data[2] += "/?"+uri.substr(1);//new url
		if (data[3] != null){
			Menu._append(data[3], uri);
		}
	},
	_append:function(subData, uri){
		for (var d=0, len=subData.length; d < len; ++d){
			var f = subData[d][2].indexOf("&filter=");
			if (f != -1 && uri.indexOf("&filter=") == 0){
				uri = Menu._fixCollision(subData[d][2].substr(f), uri);
			}
			subData[d][2] += uri;
			if (subData[d][3]){
				Menu._append(subData[d][3], uri);
			}
		}
	},
	_splitFilter: function(url){
		var filters = url.substr(8).split(";");
		var newfilter = {};
		for (var a=0, len = filters.length; a < len; ++a){
			var filter = filters[a].indexOf("="), filterKey, filterVal;
			if (filter != -1){
				filterKey = filters[a].substr(0, filter);
				filterVal = filters[a].substr(filter + 1)
			}else{
				filterKey = filters[a];
				filterVal = "";
			}
			newfilter[filterKey] = filterVal;
		}
		return newfilter
	},
	_fixCollision:function(url, uri){
		var s = Menu._splitFilter(url), f = Menu._splitFilter(uri);
		var newurl = "";
		for (var a in f){
			if (!s[a] && a != "sl" && a != "cl"){
				newurl += ";";
				newurl += a + "=" + f[a];
			}
		}
		return newurl;
	},
	//data[i][0]=index
	fixUrls: function(data, uri, filter, unUseFilter, ki){
		if (!ki){
			ki = 0;
		}
		for (var i=0, len=data.length; i<len; ++i){
			if (data[i][2] == null){
				data[i][2] = uri + data[i][0] + (filter ? filter : "");
			}
			if (data[i][3]){
				if (unUseFilter == true || (typeof unUseFilter == "object" && unUseFilter[ki] == true)) {
					Menu.fixUrls(data[i][3], uri, filter, unUseFilter, ki+1);
				}else {
					Menu.fixUrls(data[i][3], uri + data[i][0] + "_", filter, unUseFilter, ki+1);
				}
			}
		}
	},
	/**
	 * 在parent层上创建目录按钮
	 * 
	 * @param {Object} parent
	 * @param {Object} data
	 * 
	 * 目录结构为
	 * [index, name, url, submenu]
	 * submenu与主目录结构相同
	 */
	addButtons:function(parent, data){
		for (var i=0, len=data.length; i<len; ++i){
			//index
			if (data[i][0] == null){
				continue;
			}
			var $a = $("<a/>"), $span = $("<span/>");
			//url
			if (data[i][2]){
				$a.attr("href", data[i][2]);
			}else{
				$a.attr("href", "javascript:;");
				$a.css({
					"cursor": "default",
					"text-decoration": "none"
				});				
			}
			//submenu
			if (data[i][3] != null){
				$span.addClass("menuarrowd");
				$a[0].menu = data[i][3];//data数据必须存入$a元素中
				$a.mouseover(Menu.show);
				$a.mouseout(Menu.hide);
			}else{
				$span.css("margin-right", "8px");
				$a.mouseover(Menu._hide);
			};
			$span.text(data[i][1]).appendTo($a);
			$a.appendTo(parent);
		}
	}
}

Menu.fixUrls(mn_items, "/item/index.php?id=");
Menu.fixUrls(mn_npcs, "/npc/index.php?id=");
Menu.fixUrls(mn_pets, "/pet/index.php?type=");
Menu.fixUrls(mn_achievements, "/achievement/index.php?id=", null, true);
Menu.fixUrls(mn_factions, "/faction/index.php?type=", null);
Menu.fixUrls(mn_quests, "/quest/index.php?id=");
Menu.fixUrls(mn_spells, "/spell/index.php?id=");
Menu.fixUrls(mn_itemSets, "/itemset/index.php?id=");

/**
 * 
 * @param {Object} cfg
 */
function Tabs(cfg){
	$.extend(this, cfg);
	if (!this.parent){return;}
	
	this.oldMode = false;
	this.selectedTab = -1;
	this.uls = [];
	this.tabs = [];
	this.nShows = 0;
	if (this.poundable == null){
		this.poundable = 1;
	}
	this.poundedTab = null;
	if (this.onLoad == null){
		this.onLoad = Tabs.onLoad.bindContext(this)
	}
	if (this.onShow == null){
		this.onShow = Tabs.onShow.bindContext(this)
	}
	if (this.onHide){
		this.onHide = Tabs.onHide.bindContext(this)
	}
}
Tabs.prototype = {
	add:function(name, cfg){
		var options, tabIndex = this.tabs.length;
		options = {
			caption: name,
			index: tabIndex,
			owner: this
		}
		$.extend(options, cfg);
		this.tabs.push(options);
		return tabIndex;
	},
	del:function(tabIndex){
		if (this.tabs[tabIndex]){
			$("#tab-"+this.tabs[tabIndex].id).hide();
			this.selectedTab = -1;
			this.uls = [];
			this.tabs.splice(tabIndex, 1);
			this.nShows = 0;
			this.parent.empty();
			this.flush();
		}
	},
	focus:function(id){
		if (id < 0){
			id = this.tabs.length + id;
		}
		this.forceScroll = 1;
		var _lnk = this.uls[2].find("a")[id];
		$(_lnk).trigger("click", [{}, true]);
		this.forceScroll = null
	},
	show:function(tabIndex, tabObj){
		var selectedTab;
		if (isNaN(tabIndex) || tabIndex < 0){
			tabIndex = 0;
		}else{
			if (tabIndex >= this.tabs.length){
				tabIndex = this.tabs.length - 1;
			}
		}		
		if (tabObj == null && tabIndex == this.selectedTab){
			return;
		}
		if (this.selectedTab != -1) {
			selectedTab = this.tabs[this.selectedTab];
			if (this.onHide && !this.onHide(selectedTab)){
				return;
			}
			if (selectedTab.onHide && !selectedTab.onHide()){
				return;
			}			
		}++this.nShows;
		var mode = this.oldMode ? 0 : 3;
		for (f = 0; f <= mode; ++f){
			var $lnks = this.uls[f].find("a"), _lnk;
			if (this.selectedTab != -1) {
				_lnk = $($lnks[this.selectedTab]);				
				_lnk.removeClass();
			}
			_lnk = $($lnks[tabIndex]);
			_lnk.addClass("selected");
		}
				
		selectedTab = this.tabs[tabIndex];
		if (selectedTab.onLoad){
			selectedTab.onLoad();
			selectedTab.onLoad = null;
		}
		this.onShow(this.tabs[tabIndex], this.tabs[this.selectedTab]);
		if (selectedTab.onShow){
			selectedTab.onShow(this.tabs[this.selectedTab]);
		}
		this.selectedTab = tabIndex;
	},
	flush:function(tabIndex){
		if (this.oldMode){
			
		}else{
			var main, tablvl;
			var tabContainer = $("<div/>").addClass("tabs-container");
			main = $("<div/>").appendTo(tabContainer).css("visibility", "hidden");
			this.uls[0] = $("<ul/>").addClass("tabs").appendTo(main);
			tablvl = $("<div/>").addClass("tabs-levels");
			for (var j=1; j <= 3; ++j){
				var tl = $("<div/>").addClass("tabs-level");
				this.uls[j] = $("<ul/>").addClass("tabs").css("top", -30 * (3-j) + "px").appendTo(tl);
				tl.appendTo(tablvl);
			}
			tablvl.appendTo(tabContainer)
			for (k = 0; k < this.tabs.length; ++k){
				var tab = this.tabs[k];
				for (var r = 0; r<= 3; ++r){
					var _li = $("<li/>"), _lnk = $("<a/>"), _b = $("<b/>");
					if (this.poundable){
						_lnk.attr("href", "#"+tab.id);
					}else{
						_lnk.attr("href", "javascript:;");
					}
					if (r > 0){
						_lnk.bind("click", Tabs.onClick.bindContext(tab, _lnk))
					}
					if (!$.browser.msie6){
						$("<div/>").text(tab.caption).appendTo(_lnk);
					}
					_b.text(tab.caption).appendTo(_lnk);
					_lnk.appendTo(_li);
					_li.appendTo(this.uls[r]);
				}
				tabContainer.appendTo(this.parent);
			}
		}
		if (this.onLoad){
			var _u = this.onLoad();
			if (_u != null){
				this.poundedTab = tabIndex = _u
			}
		}
		this.show(tabIndex);
	},
	setTabName:function(tabIndex, name){
		var mode = this.oldMode ? 0 : 3;
		this.tabs[tabIndex].caption = name;
		for (var t = 0; t < mode; ++t){
			//var _lnk = this.uls[t].find("a")[id];
		}
	},
	setTabPound:function(){
		if (!this.poundable){return;}
		
		var mode = this.oldMode ? 0 : 3;
		for (var k = 0; k <= mode; ++k){
			//var _lnk = this.uls[t].find("a")[id];
		}
	},
	getSelectedTab:function(){
		return this.selectedTab;
	}
}
Tabs.onShow = function(data, tabObj){
	var container;
	if (tabObj){
		$("#tab-"+tabObj.id).hide();
	}
	container = $("#tab-"+data.id);
	container.show();
	if ((this.nShows == 1 && this.poundedTab != null && this.poundedTab >= 0) || this.forceScroll){
		var target, scrlen;
		if (this.__st){
			target = this.__st
			scrlen = 15
		}else{
			target = container;
			scrlen = this.parent.height() + 15;
		}
		if ($.browser.msie){
			
		}else{
			
		}
	}	
}
Tabs.onLoad = function(){
	if (!this.poundable || !location.hash.length){
		return
	}
	var hash = location.hash.substr(1).split(":")[0];
	if (hash){
		return in_array(hash, this.tabs, true, function(tabs){
			return tabs.id;
		})
	}
}
Tabs.onClick = function(lnk, e, tabObj){
	if (tabObj == null && this.index == this.owner.selectedTab){
		return;
	}
	//e = getInfoFromEvent(e);
	this.owner.show(this.index, tabObj);
	if (this.owner.poundable){
		var hindex = lnk.attr("href").indexOf("#");
		hindex != -1 && location.replace(lnk.attr("href").substr(hindex));
	}
	return false
}


var ws_listviews = {};
/**
 * 
 * @param {Object} option
 * type select type's template
 * id
 * parent
 * {Object}data
 * {Function}customFilter
 */
function LightView(option){
	$.extend(this, option);//数据合并
	if (this.id){
		var newid = (this.tabs ? "tab-" : "lv-") + this.id;
		if (this.parent){
			if (typeof this.parent == "string") {
				this.parent = $("#" + this.parent);
			}else{
				this.parent = this.parent
			}			
			var newcon = $("<div/>").attr("id", newid).appendTo(this.parent)//
			this.container = newcon;
		}else{
			this.container = $("#"+newid);
		}
	}else{ return; }
	
	if (this.type && LightView.templates[this.type]){
		this.type = LightView.templates[this.type];
	}else{return;}
	
	ws_listviews[this.id] = this;
	if (this.data == null){this.data = []}
	
	if (this.poundable == null){
		if (this.type.poundable != null){
			this.poundable = this.type.poundable;
		}else{
			this.poundable = true
		}
	}	
	if (this.searchable == null){
		if (this.type.searchable != null){
			this.searchable = this.type.searchable;
		}else{
			this.searchable = false;
		}
	}	
	if (this.filtrable == null){
		if (this.type.filtrable != null){
			this.filtrable = this.type.filtrable;
		}else{
			this.filtrable = false;
		}
	}	
	if (this.data.length == 1){
		this.searchable = false;
		this.filtrable = false;
	}
	if (this.searchable && this.searchDelay == null){
		if (this.type.searchDelay != null){
			this.searchDelay = this.type.searchDelay;
		}else{
			this.searchDelay = 333;
		}
	}	
	if (this.clickable == null){
		if (this.type.clickable != null){
			this.clickable = this.type.clickable;
		}else{
			this.clickable = true;
		}
	}	
	if (this.hideBands == null){
		this.hideBands = this.type.hideBands;
	}	
	if (this.hideNav == null){
		this.hideNav = this.type.hideNav;
	}	
	if (this.hideHeader == null){
		this.hideHeader = this.type.hideHeader;
	}	
	if (this.hideCount == null){
		this.hideCount = this.type.hideCount
	}	
	if (this.computeDataFunc == null && this.type.computeDateFunc != null){
		this.computeDataFunc = this.type.computeDateFunc;
	}
	
	if (this.createCbControls == null && this.type.createCbControls != null){
		this.createCbControls = this.type.createCbControls;
	}
	
	if (this.type.onBeforeCreate != null){
		if (this.onBeforeCreate == null){
			this.onBeforeCreate = this.type.onBeforeCreate;
		}else{
			this.onBeforeCreate = [this.onBeforeCreate, this.type.onBeforeCreate];
		}
	}	
	if (this.onAfterCreate == null && this.type.onAfterCreate != null) {
        this.onAfterCreate = this.type.onAfterCreate
    }
	if (this.createNote == null && this.type.createNote != null) {
        this.createNote = this.type.createNote
    }
	
	if (this.customFilter == null && this.type.customFilter != null){
		this.customFilter = this.type.customFilter;
	}
	
	if (this.onSearchSubmit == null && this.type.onSearchSubmit != null){
		this.onSearchSubmit = this.type.onSearchSubmit;
	}
	
	if (this.clip == null && this.type.clip != null){
		this.clip = this.type.clip
	}	
	
	if (this.mode == null) {
        this.mode = this.type.mode
    }
	
	if (this.nItemsPerPage == null){
		if (this.type.nItemsPerPage != null){
			this.nItemsPerPage = this.type.nItemsPerPage;
		}else{
			this.nItemsPerPage = 50;
		}
	}	
	this.nItemsPerPage |= 0;
	if (this.nItemsPerPage <= 0){
		this.nItemsPerPage = 0;
	}
	this.nFilters = 0
	this.resetRowVisibility();
	if (this.mode == LightView.MODE_TILED) {
		if (this.nItemsPerRow == null){
			var pr = this.type.nItemsPerRow;
			this.nItemsPerRow = (pr != null ? pr : 4);
		}
		this.nItemsPerRow |= 0;
		if (this.nItemsPerRow < 1){
			this.nItemsPerRow = 1;
		}
	}else {
		this.nItemsPerRow = 1;
	}
	
	this.columns = [];
	for (var c = 0, len = this.type.columns.length; c < len; ++c){
		var data = this.type.columns[c], obj = {};
		$.extend(obj, data);
		this.columns.push(obj);
	}
	
	if (this.extraCols != null){
		for (var f = 0; f < this.extraCols.length; ++f){
			var sindex = null;
			var _func = this.extraCols[f];
			if (_func.after || _func.before){
				
			}
			if (sindex == null){
				sindex = this.columns.length;
			}
			this.columns.splice(sindex, 0, _func);
		}
	}	
	this.visibility = [];
	var visbleCols = [], hiddenCols = [];
	
	if (this.visibleCols != null){
		array_walk(this.visibleCols, function(b){
			visbleCols[b] = 1;
		});
	}
	if (this.hiddenCols != null){
		array_walk(this.hiddenCols, function(b){
			hiddenCols[b] = 1;
		})
	}
	for (var col = 0, len = this.columns.length; col < len; ++col){
        var column = this.columns[col];
        if (visbleCols[column.id] != null || (!column.hidden && hiddenCols[column.id] == null)) {
            this.visibility.push(col);
        }
    }
	
	/**
	 * @param Object this.sort
	 */
	if (this.sort == null && this.type.sort){
		this.sort = this.type.sort.slice(0);
	}else{
		if (this.sort != null){
			var orgSort = this.sort;
			this.sort = [];//reset
			for (var s= 0; s< orgSort.length; ++s){
				var v = parseInt(orgSort[s]);
				if (isNaN(v)){
					//hyphen
					var hasPhen = 0;
					if (orgSort[s].charAt(0) == "-"){
						hasPhen = 1;
						orgSort[s] = orgSort[s].substring(1);
					}					
					
					var callval = in_array(orgSort[s], this.columns, true, function(data){						
						return data.id
					});
					if (callval != -1){
						if (hasPhen){
							this.sort.push(-(callval+1));
						}else{
							this.sort.push(callval+1);
						}
					}
				}else{
					this.sort.push(v);
				}
			}
		}else{
			this.sort = [];
		}
	}
	
	if (this.tabs) {
		this.tabIndex = this.tabs.add(this.getTabName(), {
			id : this.id,
			onLoad: this.init.bindContext(this)
		})
	}else {
		this.init();
	}
}

LightView.MODE_DEFAULT = 0;
LightView.MODE_CHECKBOX = 1;
LightView.MODE_DIV = 2;
LightView.MODE_TILED = 3;
LightView.prototype.init = function(){
	if (this.data.length){
		if (this.computeDataFunc != null){
			for (var s=0; s < this.data.length; ++s){
				this.computeDataFunc(this.data[s])
			}
		}	
	}
	if (this.tabs){
		this.pounded = (this.tabs.poundedTab == this.tabIndex);
		if (this.pounded){
			this.readPound();
		}
	}else{
		this.readPound();
	}
	
	var onbeforeCreate;
	if (this.onBeforeCreate != null) {
		if (typeof this.onBeforeCreate == "function") {
			onbeforeCreate = this.onBeforeCreate();
		}
		else {
			for (var i = 0; i < this.onBeforeCreate.length; ++i) {
				(this.onBeforeCreate[i].bindContext(this))();
			}
		}
	}
	
	//this.noData;
	if (this.mode == LightView.MODE_DIV){
		this.maincontainer = this.mainDiv = $("<div />").addClass("lightview-mode-div");		
	}else{
		//this.container.addClass("lightview-contents");
		this.maincontainer = this.table = $("<table />");
		this.thead = $("<thead/>");
		this.tbody = $("<tbody/>");
		if (this.clickable){
			this.tbody.addClass("clickable")
		}		
		if (this.mode == LightView.MODE_TILED){
			this.tbody.addClass("lightview-mode-tiled");
			
		}else{
			this.table.addClass("lightview-mode-default");
			this.createHeader();
			this.updateSortArrow();
		}
		this.thead.appendTo(this.table);
		this.tbody.appendTo(this.table);
		if (this.mode == LightView.MODE_CHECKBOX && $.browser.msie){
			setTimeout(LightView.cbIeFix.bindContext(this), 1);
		}	
	}
	this.createBands();
	if (this.customFilter != null){
		this.updateFilters();
	}
	this.updateNav();
	this.refreshRows();
	if (this.onAfterCreate != null){
		this.onAfterCreate(onbeforeCreate);
	}
}
LightView.prototype.createHeader = function(){
	var $tr = $("<tr />");
	if (this.mode == LightView.MODE_CHECKBOX){
		var $tg = $("<th/>").width(33).appendTo($tr);
		$("<a/>").attr("href", "javascript:;").addClass("lightview-cb").text(String.fromCharCode(160)).appendTo($("<div/>").appendTo($tg));
	}
	for (var i = 0, leng = this.visibility.length; i < leng; ++i){
		var v = this.visibility[i], column = this.columns[v], $th = $("<th />"), $div = $("<div />"),$lnk = $("<a />").attr("href", "javascript:;"),
		outerSpan = $("<span />"), innerSpan = $("<span />");
		column.__th = $th;		
		if (this.filtrable && (column.filtrable == null || column.filtrable)){
			$lnk.bind("mouseup", LightView.headerClick.bindContext(this, column, v));
			$lnk.click(function(){return false})
			$lnk[0].oncontextmenu = function(){return false};
		}else{
			$lnk.click(this.sortBy.bindContext(this, v+1))
		}
		$lnk.bind("mouseover", LightView.headerOver.bindContext(this, $lnk, column));
		$lnk.bind("mouseout", Tooltip.hide)
		ns($lnk);
		if (column.width != null){
			$th.width(column.width)
		}		
		if (column.align != null){
			$th.css("text-align", column.align);
		}		
		if (column.span != null){
			$th.attr("colSpan", column.span);
		}
		innerSpan.text(column.name);
		innerSpan.appendTo(outerSpan);
		outerSpan.appendTo($lnk);
		$lnk.appendTo($div);
		$div.appendTo($th);
		$th.appendTo($tr);
	}
	if (this.hideHeader){
		this.thead.hide();
	}
	$tr.appendTo(this.thead);
}
LightView.prototype.createBands = function(){
	this.bandTop = $("<div/>").addClass("lightview-band-top").appendTo(this.container);
	this.bandBot = $("<div/>").addClass("lightview-band-bottom");
	this.noteTop = $("<div />").addClass("lightview-note");
	this.noteBot = $("<div />").addClass("lightview-note");
	
	if (this.note){
		this.noteTop.html(this.note)
	}else{
		if (this.createNote) {
			this.createNote(this.noteTop, this.noteBot);
		}
	}
	if (this.noteTop.contents().length == 0){
		this.noteTop.append(String.fromCharCode(160))
	}	
	this.noteBot.text(String.fromCharCode(160));
	
	//导航栏 页码翻滚
	this.navTop = this.createNav(true);
		this.navTop.appendTo(this.bandTop);	
	if (this.searchable){
		var ftrfunc = this.updateFilters.bindContext(this, true);
		var c = (this._truncated ? "search-within-results2" : "search-within-results");//show text
		var span = $("<span />").addClass("lightview-quicksearch").appendTo(this.bandTop);
		this.quickSearchBox = $("<input />").attr("type", "text").attr("placeholder", "请输入您要搜索的内容");
		this.quickSearchGlass = $("<em />").appendTo(span);
		this.quickSearchClear = $("<a />").attr("href", "javascript:;").appendTo(span).hide();
		this.quickSearchClear.bind("click", function(){
			var _lnk = this.nextSibling;
			_lnk.value = "";
			_lnk.className = c;
			ftrfunc();
		});
		this.quickSearchClear.append("<span/>");
		
		var sb = this.quickSearchBox;
		sb.width(this._truncated ? "19em" : "15em");
		
		onAfterTyping(sb, ftrfunc, this.searchDelay);
		sb.bind("mouseover", function(){
			if ($.trim(this.value) != ""){
				this.className = "";
			}
		})
		sb.bind("focus", function(){
			this.className = "";
		});
		
		sb.bind("blur", function(){
			if ($.trim(this.value) == "") {
				this.className = c;
				this.value = "";
			}
		})
				
		sb.bind("keypress", this.submitSearch.bindContext(this))
		
		if ($.browser.msie){
			setTimeout(function(){
				sb.val("");
			}, 1);
		}
		
		this.quickSearchBox.appendTo(span);
		span.appendTo(this.bandTop);
	}
	
	this.noteTop.appendTo(this.bandTop);
	this.navBot = this.createNav(false);
		this.navBot.appendTo(this.bandBot);
	this.noteBot.appendTo(this.bandBot);
	if (this.mode == LightView.MODE_CHECKBOX){
		if (this.node){
			this.noteTop.css("padding-bottom", "5px");
		}
		this.cbBarTop = this.createCbBar(true);
		//this.cbBarBot = this.createCbBar(false);
		
		this.cbBarTop.appendTo(this.bandTop);
	}
	if (this.hideBands & 1){
		this.bandTop.hide();
	}	
	if (this.hideBands & 2){
		this.bandBot.hide();
	}
	
	if (this.clip){
		var $clip = $("<div />").addClass("lightview-clip").width(this.clip.w).height(this.clip.h);
		this.clipDiv = $clip;
		this.maincontainer.appendTo(this.clipDiv);
		this.clipDiv.appendTo(this.container);
	}else{
		this.maincontainer.appendTo(this.container);
	}
	this.bandBot.appendTo(this.container);
}
LightView.prototype.createNav = function(status){
	var $nav = $("<div />").addClass("lightview-nav");
	var $first = $("<a />").attr("href", "javascript:;").text(String.fromCharCode(171) + "首页").appendTo($nav).click(this.firstPage.bindContext(this));
	var $pre = $("<a />").attr("href", "javascript:;").text(String.fromCharCode(8249) + "上一页").appendTo($nav).click(this.previousPage.bindContext(this));
	var page = $("<span />").appendTo($nav);
	var $next = $("<a />").attr("href", "javascript:;").text("下一页" + String.fromCharCode(8250)).appendTo($nav).click(this.nextPage.bindContext(this))
	var $last = $("<a />").attr("href", "javascript:;").text("末页" + String.fromCharCode(187)).appendTo($nav).click(this.lastPage.bindContext(this));
	
	var fpage = $("<b/>").appendTo(page);
	page.append(" - ");
	var lpage = $("<b/>").appendTo(page);
	page.append(" @ ");
	var tpage = $("<b/>").appendTo(page);
		
	if (status){
		if (this.hideNav & 1) {
			$nav.hide()
		}
	}else{
		if (this.hideNav & 2) {
			$nav.hide();
		}
	}	
	return $nav;
}
LightView.prototype.createCbBar = function(site){
	var cbBar = $("<div/>");
	if (this.createCbControls){
		this.createCbControls(cbBar, site)
	}
	if (cbBar.children(":first")){
		cbBar.addClass("lightview-withselected" + (site ? "" : "2"));
	}
	return cbBar;
}
LightView.prototype.getTabName = function(){
	var name = this.name, len = this.data.length;
	for (var k = 0; k < this.data.length; ++k){
		if (this.data[k].__hidden || this.data[k].__deleted){
			--len;
		}
	}
	if (len > 0 && !this.hideCount){
		name += "("+len+")";
	}
	return name
}
LightView.prototype.getTabPound = function(){
	var s = "";
	s += this.rowOffset;
	if (this.poundable != 2 && this.sort.length){
		s += ("+"+this.sort.join("+")).replace(/\+\-/g, "-");
	}
	return s
}
LightView.prototype.getCheckedRows = function(){
	
}
LightView.prototype.refreshRows = function(){
	var maincontainer = (this.mode == LightView.MODE_DIV) ? this.maincontainer : this.tbody;
	maincontainer.empty();
	var rowOffset, rowVisible;
	if (this.nRowsVisible == 0){
		this.showNodata();
		return
	}
	
	if (!(this.hideBands & 1)){
		this.bandTop.show()
	}
	
	if (!(this.hideBands & 2)){
		this.bandBot.show();
	}
	
	if (this.nItemsPerPage > 0){
		rowOffset = this.rowOffset;
		rowVisible = Math.min(rowOffset + this.nRowsVisible, rowOffset + this.nItemsPerPage);
		if (this.filtered && this.rowOffset > 0){
			for (var f=0, j = 0; f < this.data.length && j < this.rowOffset; ++f){
				var data = this.date[f];
				if (data.__hide || data.__deleted){
					++rowOffset
				}else{
					++j;
				}
			}
			rowVisible += (rowOffset - this.rowOffset);
		}
	}else{
		rowOffset = 0;
		rowVisible = this.nRowsVisible;
	}
	var rowCount = rowVisible - rowOffset;//显示数量-offset	
	if (this.mode == LightView.MODE_DIV){		
		for (var g=0; g < rowCount; ++g){
			var index = rowOffset + g, data = this.data[index];
			if (!data){break;}
			if (data.__hidden || data.__deleted){
				++rowCount;
				continue;
			}
			this.getDiv(index).appendTo(this.mainDiv);
		}
	}else{
		if (this.mode == LightView.MODE_TILED){
			
		}else{
			for (var row = 0; row < rowCount; ++row){
				var index = rowOffset + row,
				data = this.data[index];
				if (!data){
					break;
				}
				if (data.__hidden || data.__deleted){
					++rowCount
					continue;
				}				
				this.getRow(index).appendTo(this.tbody)
			}
		}
	}
	this.maincontainer.css("display", "");
}
LightView.prototype.getDiv = function(rindex){
	var data = this.data[rindex];
	if (data.__div == null){
		this.createDiv(data, rindex)
	}
	return data.__div
}
LightView.prototype.createDiv = function(data, index){
	var $div = $("<div />");
	data.__div = $div;
	(this.type.compute.bindContext(this, data, $div, index))();
}
LightView.prototype.getCell = function(index){
	
}
LightView.prototype.createCell = function(data, index){
	
}
LightView.prototype.getRow = function(rindex){
	var data = this.data[rindex];
	if (data.__tr == null){
		this.createRow(data);
	}
	return data.__tr
}
LightView.prototype.setRow = function(index){
	
}
LightView.prototype.createRow = function(data){
	var tr = $("<tr />");
	data.__tr = tr;
	if (this.mode == LightView.MODE_CHECKBOX){
		var $td = $("<td/>").appendTo(tr);
		if (!data.__nochk) {
			$td.addClass("lightview-cb");
			$td[0].onclick = LightView.cbCellClick;
			var checkbox = $("<input />").attr("type", "checkbox");
			checkbox[0].onclick = LightView.cbClick;
			if (data.__chk){
				checkbox.attr("checked", true);
				if ($.browser.msie){
					checkbox.attr("defaultChecked", true);
				}
			}
			data.__cb = checkbox;
			checkbox.appendTo($td);
		}		
	}	
	for (var d = 0; d<this.visibility.length; ++d){
		var cid = this.visibility[d], column = this.columns[cid], $td = $("<td />"), $diver;
		if (column.align != null){
			$td.css("text-align", column.align);
		}
		if (column.compute){
			$diver = (column.compute.bindContext(this, data, $td, tr, cid))()
		}else{
			if (data[column.value] != null){
				$diver = data[column.value];
			}else{
				$diver = -1;
			}
		}
		if ($diver != -1 && $diver != null){
			var l = $td.children(":first").length
			if (l == 0) {
				$td.text($diver)
			}else {
				$td.children(":first").before($diver);
			}
		}
		$td.appendTo(tr);
	}
	if (this.mode == LightView.MODE_CHECKBOX && data.__chk){
		tr.attr("class", "checked");
	}
	if (this.type.getItemLink){
		//tr[0].onclick = this.itemClick.bindContext(this, data);
	}
	if ($.browser.msie6){
		tr[0].onmouseover = LightView.itemOver;
		tr[0].onmouseout = LightView.itemOut;
	}
};
LightView.prototype.itemClick = function(data, e){
	e = getInfoFromEvent(e);
	var count = 0, target = e._target;	
	while (target && count < 3){
		if (target.nodeName == "A"){
			return;
		}
		target = target.parentNode;
	}
	location.href = this.type.getItemLink(data);
}

LightView.prototype.showNodata = function(){
	//comments-contents
	this.noData = this.maincontainer
	if (this.type.onNoData){
		this.type.onNoData.bindContext(this, this.noData)();
	}
}
LightView.prototype.resetRowVisibility = function(){
	for (var i = 0; i<this.data.length; ++i){
		this.data[i].__hidden = false;
	}
	this.filtered = false;
	this.rowOffset = 0;
	this.nRowsVisible = this.data.length;
}
LightView.prototype.validatePage = function(){
	var perpage = this.nItemsPerPage, rowOffset = this.rowOffset, rowvisible = this.nRowsVisible;
	if (rowOffset < 0){
		this.rowOffset = 0
	}else{
		this.rowOffset = this.getRowOffset(rowOffset + perpage > rowvisible ? rowvisible - 1 : rowOffset);
	}
}
LightView.prototype.getRowOffset = function(rowoffsets){
	var perpage = this.nItemsPerPage;
	return (perpage > 0 && rowoffsets > 0 ? Math.floor(rowoffsets / perpage) * perpage : 0)
}
LightView.prototype.changePage = function(){
	this.validatePage();
	this.refreshRows();
	this.updateNav();
	this.updatePound();
}
LightView.prototype.firstPage = function(){
	this.rowOffset = 0;
	this.changePage();
	return false;
}
LightView.prototype.previousPage = function(){
	this.rowOffset -= this.nItemsPerPage;
	this.changePage();
	return false;
}
LightView.prototype.nextPage = function(){
	this.rowOffset += this.nItemsPerPage;
	this.changePage();
	return false;
}
LightView.prototype.lastPage = function(){
	this.rowOffset = 99999999999999999999999999999;
	this.changePage();
	return false;
}
LightView.prototype.deleteRows = function(data){
	if (!data || !data.length){
		return;
	}
	for (var i = 0; i<data.length; ++i){
		var f = data[i];
		if (!f.__hidden && !f.__hidden) {
			this.nRowsVisible -= 1
		}
		f.__deleted = true
	}
	if (this.rowOffset > this.nRowsVisible){
		this.previousPage();
	}else{
		this.refreshRows();
		this.updateNav()
	}
}
LightView.prototype.getClipDiv = function(){
	return this.clipDiv
}
LightView.prototype.getNoteTopDiv = function(){
	return this.noteTop;
}
LightView.prototype.getColText = function(data, column){
	if (column.getVisibleText){
		return column.getVisibleText(data)
	}	
	if (column.getValue){
		return column.getValue(data)
	}	
	if (column.value){
		return data[column.value]
	}	
	if (column.compute){
		return column.compute(data)
	}	
	return "";
}
LightView.prototype.updateFilters = function(refresh){
	Tooltip.hide();
	this.resetRowVisibility();
	
	var sechval, wordlist, wlen//search vals, word, wlen
	if (this.searchable){
		this.quickSearchBox.parent().show();
		sechval = $.trim(this.quickSearchBox.val());
		if (sechval){
			this.quickSearchGlass.hide();
			this.quickSearchClear.show();
			sechval = sechval.toLowerCase().replace(/\s+/g, "");
			wordlist = sechval.split(" ")
			wlen = wordlist.length;
		}else{
			this.quickSearchGlass.show();
			this.quickSearchClear.hide();
		}
	}else{
		this.quickSearchBox.parent().hide();
	}
	
	if (!sechval && this.nFilters == 0 && this.customFilter == null){
		if (refresh){
			this.updateNav();
			this.refreshRows();
		}
		return;
	}
	
	var sortA = {
		1 : function(a, b){
			return a > b;
		},
		2 : function(a, b){
			return a == b;
		},
		3 : function(a , b){
			return a < b;
		},
		4 : function(a, b){
			return a >= b;
		},
		5 : function(a, b){
			return a <= b;
		},
		6 : function(a, b, c){
			return b <= a && a <= c
		}
	}
	
	var sortB = {
		1 : function(a, b, c){
			return b > c;
		},
		2 : function(a, b, c){
			return a <= c && c <= b;
		},
		3 : function(a, b, c){
			return a < c;
		},
		4 : function(a, b, c){
			return b >= c;
		},
		5: function(a, b, c){
			return a <= c;
		},
		6: function(a, b, c, d){
			return c <= b && a <= d;
		}
	}
	
	var rowVisible = 0;
	for (var u = 0, len = this.data.length; u < len; ++u){
		var data = this.data[u], filterCount = 0;
		var nSearchMatches = 0,
        matches = [];
		data.__hidden = true;
		//g, u
		if (this.customFilter && !this.customFilter(data)){
			continue;
		}
		
		for (var v = 0, leng = this.visibility.length; v < leng; ++v){
			var cid = this.visibility[v];
			var column = this.columns[cid];
			if (column.__filter){
				var f = column.__filter, ismatch = false;
				if (column.type == null || column.type == "num" || f.type > 0){
					
				}else{
					
				}
				if (f.invert){
					ismatch = !ismatch;
				}
				if (ismatch){
					++filterCount;
				}else{
					break;
				}
			}			
			if (sechval){
				var ct = this.getColText(data, column)
				if (ct){
					ct = ct.toString().toLowerCase();
					for (var s=0; s < wordlist.length; ++s){
						if (!matches[s]){
							if (ct.indexOf(wordlist[s]) != -1){
								matches[s] = 1;
								++nSearchMatches;
							}
						}
					}
				}					
			}	
		}
		if (data.__alwaysvisible || ((this.nFilters == 0 || filterCount == this.nFilters) && (!sechval || nSearchMatches == wlen))){
			data.__hidden = false;
			++rowVisible;
		}
	}
	this.filtered = (rowVisible < this.data.length);
	this.nRowsVisible = rowVisible;	
	if (refresh){
		this.updateNav();
		this.refreshRows();
	}
	
}
//sort
/**
 * 
 * @param {Object} sorttable
 * @param {integer} sindex
 */
LightView.prototype.addSort = function(sorttable, sindex){
	var abid = in_array(Math.abs(sindex), sorttable, true, function(n){
		return Math.abs(n);
	});
	
	if (abid != -1){
		sindex = sorttable[abid];
		sorttable.splice(abid, 1);
	}
	sorttable.splice(0, 0, sindex);
}
LightView.prototype.sortBy = function(rowindex){
	if (rowindex <= 0 || rowindex > this.columns.length){
		return;
	}	
	if (Math.abs(this.sort[0]) == rowindex){
		this.sort[0] = -this.sort[0];
	}else{
		var isText = -1;
		if (this.columns[rowindex - 1].type == "text"){
			isText = 1;
		}
		this.addSort(this.sort, isText * rowindex);
	}
	
	//update
	this.applySort();
	this.refreshRows();
	this.updateSortArrow();	
	this.updatePound();
}
LightView.prototype.applySort = function(){
	if (this.sort.length == 0){return;}
	LightView.sort = this.sort;
	LightView.columns = this.columns;
	if (this.indexCreated){
		this.data.sort(LightView.sortIndexedRows);
	}else{
		this.data.sort(LightView.sortRows);
	}
	this.updateSortIndex();	
}
LightView.prototype.setSort = function(sorttable, freshrow, upound){
	if (this.sort.toString() != sorttable.toString()){
		this.sort = sorttable;
		this.applySort();
		if (freshrow){
			this.refreshRows()
		}
		if (upound){
			this.updatePound();
		}
	}
}
LightView.prototype.readPound = function(){
	if (!this.poundable || !location.hash.length){
		return (this.poundable == 2 ? false : this.applySort())
	}	
	var hash = location.hash.substr(1);
	if (this.tabs){
		var hc = hash.indexOf(":");
		if (hc == -1){
			return (this.poundable == 2 ? false : this.applySort());
		}
		hash = hash.substr(hc + 1);
	}
	var id = parseInt(hash);
	if (!isNaN(id)){
		this.rowOffset = id;
		this.validatePage();
		if (this.poundable != 2){
			var sorttable = [];
			var fid = hash.match(/(\+|\-)[0-9]+/g);
			if (fid != null){
				for (var v = fid.length - 1; v >= 0; --v){
					var sindex = parseInt(fid[v]) | 0;
					var asIndex = Math.abs(sindex);
					if (asIndex <= 0 || asIndex > this.columns.length){
						break;
					}
					this.addSort(sorttable, sindex);	
				}
				this.setSort(sorttable, false, false);		
			}
		}
		if (this.tabs){
			this.tabs.setTabPound(this.tabIndex, this.getTabPound());
		}
	}
}
LightView.prototype.updateSortArrow = function(){
	if (!this.sort.length || !this.thead){
		return;
	}
	var isInArray = in_array(Math.abs(this.sort[0]) - 1, this.visibility);
	if (isInArray == -1){return;}

	var head = this.thead.children(":first").children().eq(isInArray).children(":first").children(":first").children(":first");
	if (this.lsa && this.lsa != head){
		this.lsa.removeClass();
	}
	
	head.addClass(this.sort[0] < 0 ? "sortdesc" : "sortasc");	
	this.lsa = head;
}
LightView.prototype.updateSortIndex = function(){
	var data = this.data;
	for (var d = 0; d < data.length; ++d){
		data[d].__si = d;
	}
	this.indexCreated = true;
}
LightView.prototype.updateTabName = function(){
	if (this.tabs && this.tabIndex != null){
		this.tabs.setTabName(this.tabIndex, this.getTabName());
	}
}
LightView.prototype.updatePound = function(){
	if (!this.poundable){
		return
	}
	var pound = this.getTabPound();
	if (this.tabs){
		this.tabs.setTabPound(this.tabIndex, pound);
		location.replace("#" + this.id + ":" + pound);
	}else{
		location.replace("#" + pound)
	}
}
LightView.prototype.getCheckedRows = function(){
	var checkedRows = [];
	for (var c=0, len=this.data.length; c < len; ++c){
		var itemInfo = this.data[c];
		if ((itemInfo.__cb && itemInfo.__cb[0].checked)){
			checkedRows.push(itemInfo);
		}
	}
	return checkedRows
}
LightView.prototype.updateNav = function(){
	var nav = [this.navTop, this.navBot];
	var perPage = this.nItemsPerPage, rowOffset = this.rowOffset, rowvisible = this.nRowsVisible;
	var f = 0, p = 0, n = 0, l = 0
	if (rowvisible){
		if (!(this.hideNav & 1)) {
			nav[0].show();
		}
		if (!(this.hideNav & 2)) {
			nav[1].show();
		}
	}else{
		nav[0].hide();
		nav[1].hide();
	}
	
	if (perPage){
		if (rowOffset > 0){
			p = 1;
			if (rowOffset >= perPage){
				f = 1;
			}
		}
		if (rowOffset + perPage < rowvisible){
			n = 1;
			if (rowOffset + perPage + perPage < rowvisible){
				l = 1;
			}
		}
	}	
	for (var e = 0; e < 2; ++e){
		var navchilds = nav[e].children();
		navchilds[0].style.display = (f ? "" : "none");
		navchilds[1].style.display = (p ? "" : "none");
		navchilds[3].style.display = (n ? "" : "none");
		navchilds[4].style.display = (l ? "" : "none");
		//显示页数
		var span = nav[e].children(":eq(2)");
		span.children(":eq(0)").text(rowOffset + 1);
		span.children(":eq(1)").text(perPage ? Math.min(rowOffset + perPage, rowvisible) : rowvisible);
		span.children(":eq(2)").text(rowvisible);
	}
}
LightView.prototype.submitSearch = function(e){
	var e = getInfoFromEvent(e);
	if (!this.onSearchSubmit || e.keyCode == 13){
		return;
	}
}
LightView.prototype.focusSearch = function(){
	this.quickSearchBox.focus();
}
LightView.prototype.clearSearch = function(){
	this.quickSearchBox.val("");
}
LightView.sortRows = function(sort1, sort2){
	var sorttable = LightView.sort, columns = LightView.columns;
	for (var d = 0; d < sorttable.length; ++d){
		var cmpval, column = columns[Math.abs(sorttable[d]) - 1];
		if (column.sortFunc){
			cmpval = column.sortFunc(sort1, sort2, sorttable[d]);
		}else{
			cmpval = strcmp(sort1[column.value], sort2[column.value]);
		}
		if (cmpval != 0){
			return cmpval * sorttable[d];
		}
	}
	return 0;
}
LightView.sortIndexedRows = function(data1, data2){
	var sorttable = LightView.sort, columns = LightView.columns, column = columns[Math.abs(sorttable[0]) - 1], cmpval;
	if (column.sortFunc){
		cmpval = column.sortFunc(data1, data2, sorttable[0]);
	}else{
		cmpval = strcmp(data1[column.value], data2[column.value]);
	}
	if (cmpval != 0){
		return cmpval * sorttable[0]
	}
	return (data1.__si - data2.__si);
}
LightView.cbSelect = function(checkable){
	for (var d=0, len = this.data.length; d < len; ++d){
		var itemInfo = this.data[d];
		var checkStatus = checkable;
		if (!itemInfo.__nochk && itemInfo.__tr){
			var checkedBox = itemInfo.__tr.children(":first").children(":first");
			if (checkStatus == null){
				checkStatus = !checkedBox.attr("checked");
			}
			if (checkedBox.attr("checked") != checkStatus){
				checkedBox.attr("checked", checkStatus);
				itemInfo.__tr.css(checkedBox.attr("checked") ? "checked" : "");
				if ($.browser.msie){
					checkedBox.attr("defaultChecked", checkStatus);
					if ($.browser.msie6){
						(LightView.itemOut.bind(itemInfo.__tr))()
					}	
				}
			}
		}else{
			if (checkStatus == null){
				checkStatus = true;
			}
		}
		itemInfo.__chk = checkStatus;
	}
}
LightView.cbClick = function(e){
	setTimeout(LightView.cbUpdate.bindContext(0, 0, this, this.parentNode.parentNode), 1)
	//组织冒泡事件
	stopProp(e);
}
LightView.cbCellClick = function(){
	setTimeout(LightView.cbUpdate.bindContext(0, 1, this.firstChild, this.parentNode), 1)
	stopProp(e);
}
LightView.cbIeFix = function(){
	trs = this.tbody.find("tr");
}
LightView.cbUpdate = function(callClick, checkBox, parent){
	if (callClick){
		checkBox.checked = !checkBox.checked;
	}
	parent.className = (checkBox.checked ? "checked" : "");
	if ($.browser.msie){
		checkBox.defaultChecked = checkBox.checked;
		if ($.browser.msie6){
			(LightView.itemOver.bindContext(parent))()
		}
	}
}
LightView.itemOver = function(){
	this.style.backgroundColor = (this.className == "checked" ? "#091A25" : "#081721");
}
LightView.itemOut = function(){
	this.style.backgroundColor = (this.className == "checked" ? "#0A1D29" : "transparent");
}
LightView.headerClick = function(column, vi,e){
	e = getInfoFromEvent(e);
	if (e._button == 3 || e.shiftKey || e.ctrlKey){
		Tooltip.hide();
		setTimeout(LightView.headerFilter.bindContext(this, column, null), 1);
	}else{
		this.sortBy(vi + 1);
	}
	return false;
}
/**
 * 
 * @param {Object} column
 * @param {Object} constraint
 */
LightView.headerFilter = function(column, constraint){
	return false;
	var s = "";
	if (column.__filter){
		if (column.__filter.invert){
			s += "!";
		}
		s += column.__filter.text;
	}
	if (constraint == null){
		var constraint = prompt($.sprintf('输入对 > $1 < 的过滤条件' + (column.type == "text" ? '\r\n\r\n例如: "剑"等关键字符' : '\r\n\r\n例如: ">120", "32-34" 或者 "!<=10"等公式'), column.name), s);
	}
	if (constraint != null){
		var fconstraint = {
			text : "",
			type: -1
		};
		constraint = trim(constraint.replace(/\s+/g, " "));
		if (constraint){
			if (constraint.charAt(0) == "!" || constraint.charAt(0) == "-"){
				fconstraint.invert = 1;
				constraint = constraint.substr(1);
			}
			if (column.type == "text"){
				fconstraint.type = 0;
				fconstraint.text = constraint;
				if (fconstraint.invert){
					//fconstraint.regex = 
				}else{
					fconstraint.words = constraint.toLowerCase().split(" ");
				}
			}			
		}
	}
}
LightView.headerOver = function(lnk, column){
	var html = '';
	html += '<b class="q1">'+(column.tooltip ? column.tooltip : column.name) + "</b>";
	if (column.__filter){
		//html += "<br/>"+column.__filter.text;	
	}	
	html += '<br/><span class="q2">点击排序</span>';
	if (this.filtrable && (column.filtrable == null || column.filtrable)){
	//	html += '<br /><span class="q2">'+($.browser.opera ? "shift-点击打开自定义过滤" : "点击打开自定义过滤")+"</span>";
	}	
	Tooltip.show(lnk, html, 0, 0, "q");
}

LightView.extraCols = {
	cost: {
		id : "cost",
		name: "价格",
		getValue: function(data){
			return (data.cost[3] && data.cost[3][0] ? data.cost[3][0][1] : 0) || data.cost[2] || data.cost[1] || data.cost[0];
		},
		compute: function(data, container){
			Editor.appendMoney(container, data.cost[0], null, data.cost[1], data.cost[2], data.cost[3]);
		},
		sortFunc : function(data1, data2, sid){
			
		}
	},
	count :{
		id : "count",
		name: "掉落",
		width: "11%",
		value: "count",
		compute: function(data, container){
			if (!(this._totalCount > 0 || data.outof > 0)){
				return;
			}
			if (data.outof){
				var _d = $("<div/>").addClass("small q0").text("总计"+data.outof).appendTo(container);
			}
			return data.count;
		},
		getVisibleText: function(data){
			var count = data.count;
			if (data.outof){
				count += " "+data.outof;
			}
			return count;
		}
	},
	percent: {
		id : "percent",
		name: "掉落率",
		width: "10%",
		value: "percent",
		compute: function(data, container){
			if (data.count == -1){return "??"}
			if (data.percent >= 1.95){
				return data.percent.toFixed(0)+"%"
			}else{
				return parseFloat(data.percent.toFixed(1))+"%";
			}
		},
		getVisibleText:function(data){
			if (data.count == -1){
				return "??";
			}
			if (data.percent >= 1.95){
				return data.percent.toFixed(0)+"%"
			}else{
				return parseFloat(data.percent.toFixed(1))+"%";
			}
		}
	},
	stock : {
		id : "stock",
		name: "数量",
		width: "10%",
		value: "stock",
		compute: function(data, container){
			if (data.stock > 0){
				return data.stock;
			}else{
				container.css("font-family", "Verdana, sans-serif");
				return String.fromCharCode(8734);
			}
		},
		getVisibleText: function(data){
			if (data.stock > 0){
				return data.stock;
			}else{
				return String.fromCharCode(8734) + " infinity";
			}
		}
	}
}
LightView.templates = {
	achievement:{
		sort: [1, 2],
		nItemsPerPage: 100,
		searchable: 1,
		filtrable: 1,
		columns:[{
			id:"name",
			name: "名称",
			type: "text",
			align: "left",
			span: 2,
			value: "name",
			compute:function(data, _td, _tr){
				//data.who data.completed
				var itd = $("<td/>").css({
					"width":"1px",
					"padding":0,
					"border-right": "none"
				})
				itd.append(wsAchievements.createIcon(data.id, 1))
				//Icon.getLink()
				itd.appendTo(_tr);
				_td.css("border-left", "none");
				var _lnk = $("<a/>").attr("href", this.type.getItemLink(data)).text(data.name).appendTo(_td);
				if (data.description != null){
					var d = $("<div/>").addClass("small q0").text(data.description).appendTo(_td);
				}
			},
			getVisibleText: function(data){
				var aname = data.name;
				if (data.description){
					aname += " " + data.description;
				}
				return aname;
			}
		},
		{
			id: "location",
			name: "区域",
			type: "text",
			width: "15%",
			hidden: true,
			compute:function(data, container){
				if (data.zone){
					var _lnk = $("<a/>").addClass("q1").text(zones[data.zone]).appendTo(container);
				}
			},
			getVisibleText:function(data){
				return Editor.arrayText(data.zone, zones);
			},
			sortFunc:function(data1, data2){
				return strcmp(zones[data1.zone], zones[data2.zone])
			}
		},
		{
			id:"side",
			name: "阵营",
			type: "text",
			width: "8%",
			compute:function(data, container){
				if (data.side && data.side != 3){
					var span = $("<span/>").addClass(data.side == 1 ? "alliance-icon" : "horde-icon").append(String.fromCharCode(160)).appendTo(container);
					span[0].onmouseover = (function(t){
						Tooltip.showAtCursor(t, g_sides[data.side], 0, 0, "q");
					})
					span[0].onmousemove =Tooltip.cursorUpdate
					span[0].onmouseout = Tooltip.hide
				}
			},
			getVisibleText:function(data){
				if (data.side){
					return g_sides[data.side];
				}
			},
			sortFunc:function(data1, data2){
				return strcmp(g_sides[data1.side], g_sides[data2.side]);
			}
		},
		{
			id:"points",
			name:"点数",
			type: "number",
			width: "10%",
			value: "points",
			compute:function(data, container){
				if (data.points){
					Editor.appendMoney(container, 0, null, 0, 0, 0, data.points);
				}
			}
		},
		{
			id:"category",
			name:"类别",
			type: "text",
			width: "15%",
			compute:function(data, container){
				container.addClass("small q1")
				if (achievement_categories[data.category]) {
					$("<a/>").attr("href", "/achievement/index.php?id=" + data.category).text(achievement_categories[data.category]).appendTo(container);
				}
			},
			getVisibleText:function(data){
				if (achievement_categories[data.category]) {
					return achievement_categories[data.category];
				}else{
					return "";
				}
			},
			sortFunc:function(data1, data2){
				return strcmp(achievement_categories[data1.category], achievement_categories[data2.category])
			}
		}
		],
		getItemLink: function(data){
			return "/achievement/info.php?id="+data.id;
		}
	},
	faction:{
		sort: [1],
		nItemsPerPage: -1,
		searchable: 1,
		filtrable: 1,
		columns:[{
			id: "name",
			name:"名称",
			type: "text",
			align: "left",
			value: "name",
			compute: function(data, container){
				var _lnk = $("<a/>").attr("href", this.type.getItemLink(data)).text(data.name);
				if (data.expansion){
					var ex = $("<span/>").addClass(data.expansion == 1 ? "bc-icon" : "wotlk-icon");
					_lnk.appendTo(ex);
					ex.appendTo(container);
				}else{
					_lnk.appendTo(container);
				}
			},
			getVisibleText: function(data){
				var fname = data.name;
				if (data.expansion == 1){
					fname += " bc";
				}else{
					if (data.expansion == 2){
						fname += " wotlk wrath"
					}
				}
				return fname;
			}
		},
		{
			id: "side",
			name: "阵营",
			type:"text",
			compute:function(data, container){
				if (data.side && data.side != 3){
					var side = $("<span/>");
					side.addClass(data.side == 1 ? "alliance-icon" : "horde-icon").append(String.fromCharCode(160));
					side[0].onmouseover = (function(t){
						Tooltip.showAtCursor(t, g_sides[data.side], 0, 0, "q");
					})
					side[0].onmousemove =Tooltip.cursorUpdate
					side[0].onmouseout = Tooltip.hide
					side.appendTo(container);
				}
			},
			getVisibleText:function(data){
				if (data.side){
					return g_sides[data.side];
				}
			},
			sortFunc:function(data1, data2){
				return strcmp(g_sides[data1.side], g_sides[data2.side]);
			}
		},
		{
			id:"category",
			name:"类别",
			type: "text",
			width: "16%",
			compute: function(data, container){
				if (data.category2 != null){
					container.addClass("small q1");
					var _lnk = $("<a/>");
					var furl = "/faction/index.php?type="+data.category2;
					if (data.category){
						furl += "_"+data.category;
					}
					_lnk.attr("href", furl);
					_lnk.text(Editor.getFactionCategory(data.category, data.category2));
					_lnk.appendTo(container);	
				}
			},
			getVisibleText:function(data){
				return Editor.getFactionCategory(data.category, data.category2);
			},
			sortFunc:function(data1, data2){
				var gfc = Editor.getFactionCategory
				return strcmp(gfc(data1.category, data1.category2), gfc(data2.category, data2.category2))
			}
		}
		],
		getItemLink: function(data){
			return "/faction/info.php?id="+data.id;
		}
	},
	item: {
		sort: [1],
		searchable: 1,
		filtrable: 1,
		columns:[{
			id: "name",
			name: "名称",
			type: "text",
			align: "left",
			span: 2,
			value: "name",
			compute: function(data, _td, _tr){
				var iconTd = $("<td/>").css({
					"width":"1px",
					"padding":0,
					"border-right": "none"
				});
				var textRange = null;
				var itemTop = null;
				if (data.stack != null){
					textRange = Editor.createTextRange(data.stack[0], data.stack[1]);
				}
				if (data.avail != null){
					itemTop = data.avail;
				}
				(wsItems.createIcon(data.id, (this.iconSize == null ? 1 : this.iconSize), textRange, itemTop)).appendTo(iconTd);
				iconTd.appendTo(_tr);
				_td.css("border-left", "none");
				var _lnk = $("<a/>").addClass("q" + (7- parseInt(data.name.charAt(0)))).css("font-family", "Verdana, sans-serif").attr("href", this.type.getItemLink(data))
				if (data.rel){
					
				}
				_lnk.text(data.name.substring(1)).appendTo(_td);
				if (data.heroic){
					
				}
			},
			getVisibleText:function(data){
				var itemName = data.name.substring(1);
				if (typeof fi_nExtraCols == "number" && fi_nExtraCols >= 5){
					
				}
				return itemName;
			}
		},
		{
			id: "level",
			name: "物品等级",
			value: "level"
		},
		{
			id: "reqlevel",
			name: "需要等级",
			value: "reqlevel",
			compute: function(data, container){
				if (data.reqlevel > 1){
					return data.reqlevel;
				}
			}
		},
		{
			id: "side",
			name: "阵营",
			value: "side",
			hidden: true
		},
		{
			id: "dps",
			name: "DPS",
			value: "dps",
			hidden: true,
			compute: function(data){
				return (data.dps || 0).toFixed(1);
			}
		},
		{
			id:"speed",
			name:"攻击速度",
			value: "speed",
			hidden: true,
			compute: function(data){
				return (data.speed || 0).toFixed(2);
			}
		},
		{
			id:"armor",
			name:"护甲",
			value: "armor",
			hidden: true,
			compute:function(data){
				if (data.armor > 0){
					return data.armor;
				}
			}
		},
		{
			id:"slot",
			name: "位置",
			type: "text",
			hidden: true,
			compute: function(data, container){
				container.css("white-space", "nowrap");
				return item_slots[data.slot];
			},
			getVisibleText: function(data){
				return item_slots[data.slot];
			},
			sortFunc: function(data1, data2){
				return strcmp(item_slots[data1.slot], item_slots[data2.slot]);
			}
		},
		{
			id: "slots",
			name:"格子数",
			value: "nslots",
			hidden: true
		},
		{
			id:"skill",
			name:"专业技能",
			value: "skill",
			hidden: true
		},
		{
			id: "type",
			name: "类别",
			type: "text",
			compute: function(data, container){
				container.addClass("small q1").css("white-space", "nowrap");
				var _lnk = $("<a/>");
				var itemClassInfo = Editor.getItemType(data.classs, data.subclass);
				_lnk.text(itemClassInfo.text);
				_lnk.attr("href", itemClassInfo.url);
				_lnk.appendTo(container);
			},
			getVisibleText: function(data){
				return Editor.getItemType(data.classs, data.subclass).text
			},
			sortFunc: function(data1, data2, sid){
				var _func = Editor.getItemType;
				return strcmp(_func(data1.classs, data1.subclass).text, _func(data2.classs, data2.subclass).text);
			}
		}	
		],
		getItemLink: function(data){
			return "/item/info.php?id="+data.id;
		},
		onBeforeCreate: function(){
			var validItem = 0;
			for (var index = 0, len = this.data.length; index < len; ++index){
				var itemInfo = this.data[index];
				if (itemInfo.slot > 0 && itemInfo.slot != 18){
					++validItem
				}else{
					itemInfo.__nochk = 1
				}
			}
			if (validItem > 0){
				this.mode = 1;
				this._nComparable = validItem;
			}
		},
		createCbControls: function(container, site){
			var compare = $("<input />").attr({
				"type": "button",
				"value": "对比"
			}).appendTo(container).addClass("searchbtn");
			var deselect = $("<input />").attr({
				"type": "button",
				"value": "取消勾选"
			}).appendTo(container).addClass("searchbtn");
			
			compare.click(this.type.compareItems.bindContext(this));
			deselect.click(LightView.cbSelect.bindContext(this, false));
		},
		compareItems:function(){
			var checkedRows = this.getCheckedRows();
			if (!checkedRows.length){
				return;
			}
			var lnks = "";
			array_walk(checkedRows, function(itemInfo){
				lnks += itemInfo.id + ";"
			});
			lnks = $.rtrim(lnks, ";");
			lnks = "/itemcompare?compare=" + lnks;
			window.open(lnks)
		}
	},
	itemset: {
		
	},
	npc: {
		sort: [1],
		nItemsPerPage: 50,
		searchable: 1,
		filtrable: 1,
		columns : [{
			id : "name",
			name: "名称",
			type: "text",
			align: "left",
			value: "name",
			compute: function(data, container){
				var _lnk = $("<a/>").text(data.name).attr("href", this.type.getItemLink(data)).appendTo(container);
				if (data.tag){
					$("<div/>").addClass("small q0").text("<"+data.tag+">").appendTo(container);
				}
			},
			getVisibleText: function(data){
				var name = data.name;
				if (data.tag){
					name += data.tag	
				}
				return name;
			}
		},
		{
			id: "level",
			name: "等级",
			type: "range",
			width: "10%",
			getMinValue: function(data){
				return data.minlevel;
			},
			getMaxValue: function(data){
				return data.maxlevel;
			},
			compute: function(data, container){
				if (data.classification){
					var cf = $("<div/>").addClass("small").text(npc_classifications[data.classification]).appendTo(container);
				}
				if (data.classification == 3){return "??";}
				if (data.minlevel >0 && data.maxlevel >0){
					if (data.minlevel != data.maxlevel){
						return data.minlevel + "-" + data.maxlevel;
					}else{
						return data.minlevel;
					}
				}
				return -1;
			},
			getVisibleText:function(data){
				var s = "";
				if (data.classification){
					s += " " + npc_classifications[data.classification];
				}
				if (data.minlevel > 0 && data.maxlevel > 0){
					s += " ";
					if (data.minlevel != data.maxlevel){
						s += data.minlevel + "-" + data.maxlevel;
					}else{
						s += data.minlevel;
					}
				}
				return s;
			},
			sortFunc : function(data1, data2, sid){
				if (sid > 0 ){
					return strcmp(data1.minlevel, data2.minlevel) || strcmp(data1.maxlevel, data2.maxlevel) || strcmp(data1.classification, data2.classification);
				}else{
					return strcmp(data1.maxlevel, data2.maxlevel) || strcmp(data1.minlevel, data2.minlevel) || strcmp(data1.classification, data2.classification);
				}
			}
		},
		{
			"id": "location",
			"name": "地域",
			"type": "text",
			compute: function(data, container){
				return Editor.location(data, container);
			},
			getVisibleText:function(data){
				return Editor.arrayText(data.location, zones);	
			},
			sortFunc:function(data1, data2, sid){
				return Editor.assocArrCmp(data1.location, data2.location, zones)
			}
		},
		{
			id : "petfamily",
			name: "宠物类型",
			type: "text",
			width: "12%",
			compute: function(data, container){
				
			},
			hidden: 1
		},
		{
			id : "type",
			name: "类型",
			type: "text",
			width: "12%",
			compute:function(data, container){
				container.addClass("small q1");
				if (npc_types[data.type]){
					$("<a/>").attr("href", "/npc/index.php?id="+data.type).text(npc_types[data.type]).appendTo(container);
				}				
			},
			getVisibleText:function(data){
				return npc_types[data.type]
			},
			sortFunc:function(data1, data2, sid){
				return strcmp(npc_types[data1.type], npc_types[data2.type]);
			}
		}
		],
		getItemLink: function(data){
			return "/npc/info.php?id="+data.id;
		}
	},
	quest: {
		sort: [1, 2],
		nItemsPerPage: 50,
		searchable: 1,
		filtrable: 1,
		columns: [{
			id : "name",
			name: "名称",
			type: "text",
			align: "left",
			value: "name",
			compute: function(data, container){
				var _lnk = $("<a/>").attr("href", this.type.getItemLink(data)).text(data.name).appendTo(container);
			}
		},
		{
			id : "level",
			name: "任务等级",
			width: "11%",
			value: "level",
			compute: function(data, container){
				if (data.type || data.daily || data.weekly){
					var qtype = $("<div/>").addClass("small").css("white-space", "nowrap")
					if (data.daily){
						if (data.type){
							qtype.append(quest_types[data.type]+"日常");
						}else{
							qtype.append("日常任务");
						}
					}else{
						if (data.weekly){
							if (data.type){
								qtype.append(quest_types[data.type]+"周常");
							}else{
								qtype.append("周常任务");
							}
						}else{
							if (data.type){
								qtype.append(quest_types[data.type])
							}
						}						
					}
					qtype.appendTo(container);
				}
				return data.level
			},
			getVisibleText: function(data){
				var str = "";
				if (data.type){
					str += " " + quest_types[data.type];
				}
				if (data.daily){
					str += " " + "日常";
				}else{
					if (data.weekly){
						str += " " + "周常";
					}
				}
				if (data.level){
					str += " " + data.level;
				}
				return str;
			},
			sortFunc: function(data1, data2, sid){
				return strcmp(data1.level, data2.level) || strcmp(data1.type, data2.type);
			}
		},
		{
			id: "reqlevel",
			name: "需求等级",
			width: "11%",
			value: "reqlevel"
		},
		{
			id: "side",
			name: "阵营",
			type: "text",
			width: "8%",
			compute: function(data, container){
				if (data.side && data.side != 3){
					var span = $("<span/>").addClass(data.side == 1 ? "alliance-icon" : "horde-icon").append(String.fromCharCode(160)).appendTo(container);
					span[0].onmouseover = (function(t){
						Tooltip.showAtCursor(t, g_sides[data.side], 0, 0, "q");
					})
					span[0].onmousemove =Tooltip.cursorUpdate
					span[0].onmouseout = Tooltip.hide
				}
			},
			getVisibleText: function(data){
				if (data.side){
					return g_sides[data.side];
				}
			},
			sortFunc: function(data1, data2, sid){
				return strcmp(g_sides[data1.side], g_sides[data2.side])
			}
		},
		{
			id: "rewards",
			name: "奖励",
			filtrable: 0,
			width: "25%",
			compute: function(data, container){
				var hasItems = (data.itemchoices != null || data.itemrewards != null);
				if (hasItems){
					var rewardsNote, choiceNote;
					if (data.itemchoices && data.itemchoices.length > 1){
						choiceNote = "选择一件";
						if (data.itemrewards && data.itemrewards.length > 0){
							rewardsNote = "还将得到";
						}
					}					
					Editor.createCenteredIcons(data.itemchoices, container, choiceNote);
					Editor.createCenteredIcons(data.itemrewards, container, rewardsNote);
				}
				if (data.xp > 0 || data.money > 0){
					var att = $("<div/>")
					if (hasItems){
						att.css("padding", "4px");
					}
					if (data.xp){
						att.append(data.xp+" 经验" + (data.money > 0 ? " + " : ""));
					}
					if (data.money){
						Editor.appendMoney(att, data.money);
					}
					att.appendTo(container);
				}
			},
			getVisibleText: function(data){
				var str = "";
				if (data.itemchoices && data.itemchoices.length){
					str += " "+"选择一件";
					if (data.itemrewards && data.itemrewards.length){
						str += " "+"还将得到";
					}
				}
				if (data.xp > 0){
					str += " "+"经验"+data.xp;
				}
				return str;
			},
			sortFunc: function(data1, data2, sid){
				var cmp1 = (data1.itemchoices != null ? data1.itemchoices.length : 0) + (data1.itemrewards != null ? data1.itemrewards.length : 0);
				var cmp2 = (data2.itemchoices != null ? data2.itemchoices.length : 0) + (data2.itemrewards != null ? data2.itemrewards.length : 0);
				return strcmp(cmp1, cmp2) || strcmp((data1.xp | 0) + (data1.money | 0), (data2.xp | 0) + (data2.money | 0))
			}
		},
		{
			id : "reputation",
			name:"声望",
			width: "14%",
			value: "id",
			hidden: true
		},
		{
			id : "category",
			name: "任务分类",
			type: "text",
			width: "16%",
			compute: function(data, container){
				if (data.category != 0){
					container.addClass("small q1");
					var _lnk = $("<a/>").attr("href", "/quest/index.php?id="+data.category2+"_" + data.category);
					if (Editor.getQuestCagetory(data.category) == null){
						//alert(data.category);
					}else{
						_lnk.text(Editor.getQuestCagetory(data.category)).appendTo(container);
					}					
				}
			},
			getVisibleText: function(data){
				return Editor.getQuestCagetory(data.category);
			},
			sortFunc: function(data1, data2, sid){
				var getQuestCagetory = Editor.getQuestCagetory
				return strcmp(getQuestCagetory(data1.category), getQuestCagetory(data2.category));
			}
		}],
		getItemLink: function(data){
			return "/quest/info.php?id="+data.id;
		}
	},
	object: {
		sort: [1],
		nItemsPerPage: 50,
		columns: [{
			id:"name",
			name: "名称",
			type: "text",
			align: "left",
			value: "name",
			compute: function(data, container){
				$("<a/>").attr("href", this.type.getItemLink(data)).text(data.name).appendTo(container);
			}
		},
		{
			"id": "location",
			name: "地域",
			type: "text",
			compute: function(data, container){
				return Editor.location(data, container);
			},
			getVisibleText:function(data){
				return Editor.arrayText(data.location, zones)
			},
			sortFunc: function(data1, data2, sid){
				return Editor.assocArrCmp(data1.location, data2.location, zones)
			}
		}],
		getItemLink: function(data){
			return "/object/info.php?id="+data.id;
		}
	},
	spell: {
		sort: [1, 2],
		searchable: 1,
		filtrable: 1,
		columns:[{
			id:"name",
			name: "名称",
			type: "text",
			align: "left",
			span: 2,
			value: "name",
			compute: function(data, _td, _tr){
				var $td = $("<td/>").css({
					"width" : "44px",
					"padding": 0,
					"border-right": 0
				}), _icon;
				if (data.creates != null){
					_icon = wsItems.createIcon(data.creates[0], 1, Editor.createTextRange(data.creates[1], data.creates[2]));
				}else{
					_icon = wsSpells.createIcon(data.id, 1);
				}
				_icon.css("float", "left").appendTo($td);
				$td.appendTo(_tr);
				_td.css("border-left", "none");
				var spellDiv = $("<div/>");
				var _lnk = $("<a/>");
				var quality = data.name.charAt(0);
				if (quality != "@"){
					_lnk.addClass("q"+(7-parseInt(quality)));
				}
				_lnk.attr("href", this.type.getItemLink(data))
				_lnk.text(data.name.substring(1));
				_lnk.appendTo(spellDiv);
				if (data.rank){
					
				}
				if (data.races != null){
					
				}
				spellDiv.appendTo(_td);
			}
		},
		{
			id:"level",
			name:"等级",
			width: "10%",
			value: "level",
			compute:function(data, container){
				if (data.level > 0){
					return data.level
				}				
			},
			hidden: true
		},
		{
			id:"school",
			name: "类型",
			type: "text",
			width: "10%",
			hidden: true,
			compute: function(data, container){
				
			}
		},
		{
			id:"reagents",
			name: "材料",
			align: "left",
			width: "9%",
			getValue: function(data){
				return (data.reagents ? data.reagents.length : 0);
			},
			compute: function(data, container){
				var need = (data.reagents != null);
				if (need){
					container.css("padding", 0);
					var reagents = data.reagents;
					var m = $("<div/>").width(44*reagents.length);
					for (var r=0; r<reagents.length; ++r){
						var rItemId = reagents[r][0];
						var rStack = reagents[r][1];
						var icon = wsItems.createIcon(rItemId, 1, rStack);
						icon.css("float", "left");
						icon.appendTo(m);
						if (this.centerReagents){
							m.css("margin", "0 auto");
						}
					}
					m.appendTo(container);
				}
			}
		},
		{
			id:"source",
			name:"来源",
			type:"text",
			width: "12%",
			hidden: true,
			compute: function(data, container){
				
			}
		},
		{
			id:"skill",
			name:"技能",
			type: "text",
			width: "16%",
			compute: function(data, _td, _tr){
				if (data.skill != null){
					var skill = $("<div/>").appendTo(_td).addClass("small");
					for (var s=0, len=data.skill.length; s < len; ++s){
						if (s > 0){
							skill.append(", ")
						}
						if (data.skill[s] == -1){
							skill.append("...");
						}else{
							//父类
							if ($.inArray(data.cat, [7, -2, -3, -5, -6, -7, 11, 9]) != -1){
								var _lnk = $("<a/>").addClass("q1");
								if ($.inArray(data.cat, [-5, -6, -7]) != -1){
									
								}else{
									_lnk.attr("href", "/spell/index.php?id="+data.cat+"_"+data.skill[s]);
								}
								_lnk.text(spell_skills[data.skill]).appendTo(skill)
							}else{
								skill.append(spell_skills[data.skill])
							}
						}
					}
				}
			}
		}
		],
		getItemLink:function(data){
			return "/spell/info.php?id="+data.id;
		},
		onBeforeCreate:function(){
			if (this.centerReagents){
				this.columns[3].align = null;
			}
		}
	},
	zone: {
		sort: [1],
		nItemsPerPage:-1,
		searchable:1,
		filtrable: 1,
		columns: [{
			id:"name",
			name:"名称",
			type: "text",
			align: "left",
			value: "name",
			compute: function(data, container){
				var _lnk = $("<a/>").attr("href", this.type.getItemLink(data)).text(data.name)
				if (data.expansion){
					$("<span/>").addClass(data.expansion == 1 ? "bc-icon" : "wotlk-icon").append(_lnk).appendTo(container);
				}else{
					_lnk.appendTo(container);
				}
			},
			getVisibleText: function(data){
				var zname = data.name;
				if (data.expansion == 1){
					zname += " bc";
				}else{
					if (data.expansion == 2){
						zname += " wotlk wrath";
					}
				}
				return zname;
			}
		},
		{
			id: "level",
			name: "等级",
			type: "range",
			width: "10%",
			getMinValue: function(data){
				return data.minlevel;
			},
			getMaxValue: function(data){
				return data.maxlevel;
			},
			compute: function(data, container){
				if (data.minlevel > 0 && data.maxlevel > 0){
					if (data.minlevel != data.maxlevel){
						return data.minlevel + "-" + data.maxlevel;
					}else{
						return data.minlevel;
					}
				}
			},
			sortFunc: function(data1, data2, sid){
				if (sid > 0){
					return strcmp(data1.minlevel, data2.minlevel) || strcmp(data1.maxlevel, data2.maxlevel);
				}else{
					return strcmp(data1.maxlevel, data2.maxlevel) || strcmp(data1.minlevel, data2.minlevel);
				}
			}
		},
		{
			id: "territory",
			name: "领地",
			type: "text",
			width: "13%",
			compute: function(data, container){
				var tag = $("<span/>");
				switch (data.territory){
					case 1:
						tag.addClass("alliance-icon");
						break;
					case 0:
						tag.addClass("horde-icon");
						break;
					case 3:
						tag.addClass("ffapvp-icon");
						break;
				}
				tag.text(zone_territories[data.territory]);
				tag.appendTo(container);
			},
			getVisibleText: function(data){
				return zone_territories[data.territory];
			},
			sortFunc: function(data1, data2){
				return strcmp(zone_territories[data1.territory], zone_territories[data2.territory]);
			}
		},
		{
			id:"instancetype",
			name: "副本类型",
			type: "text",
			compute: function(data, container){
				if (data.instance > 0){
					var tag = $("<span/>");
					if ((data.instance >= 1 && data.instance <= 5) || data.instance == 7){
						tag.addClass("instance-icon"+data.instance);
					}
					if (data.nplayers == -2){
						data.nplayers = "10/25";
					}
					var instanceType = zone_instancetypes[data.instance];
					if (data.nplayers && ((data.instance != 2 && data.instance != 5) || data.nplayers > 5)){
						instanceType += " (";
						if (data.instance == 4){
							instanceType += $.sprintf("$1vs$2", data.nplayers, data.nplayers);
						}else{
							instanceType += $.sprintf("$1 人", data.nplayers);
						}
						instanceType += ")";
					}
					tag.text(instanceType);
					tag.appendTo(container);
				}
			},
			getVisibleText:function(data){
				if (data.instance > 0){
					var instanceType = zone_instancetypes[data.instance];
					if (data.nplayers && ((data.instance != 2 && data.instance != 5) || data.nplayers > 5)){
						if (data.instance == 4) {
							instanceType += " " + $.sprintf("$1vs$2", data.nplayers, data.nplayers);
						}else{
							instanceType += " " + $.sprintf("$1 人", data.nplayers);
						}
					}
					return instanceType;
				}
			},
			sortFunc: function(data1, data2, sid){
				return strcmp(zone_instancetypes[data1.instance], zone_instancetypes[data2.instance]) || strcmp(data1.instance, data2.instance) || strcmp(data1.nplayers, data2.nplayers);
			}
		},
		{
			id: "category",
			name:"类别",
			type: "text",
			width: "15%",
			compute: function(data, container){
				container.addClass("small q1");
				$("<a/>").attr("href", "/zone/index.php?type="+data.category).text(file_zone_categories[data.category]).appendTo(container)	
			},
			getVisibleText:function(data){
				return file_zone_categories[data.category]
			},
			sortFunc: function(data1, data2, sid){
				return strcmp(file_zone_categories[data1.category], file_zone_categories[data2.category])
			}
		}
		],
		getItemLink: function(data){
			return "/zone/info.php?id="+data.id;
		}
	},
	pet :{
		sort: [1],
		nItemsPerPage: -1,
		searchable: 1,
		filtrable: 1,
		columns: [{
			id: "name",
			name: "名称",
			type: "text",
			align: "left",
			value: "name",
			span: 2,
			compute: function(data, container, tr){
				var _td = $("<td/>");
				_td.css({
					"width" : "1px",
					"padding": 0,
					"border-right": "none"
				});
				Icon.create(data.icon, 0).appendTo(_td);
				_td.appendTo(tr);
				container.css("border-left", "none");
				var m = $("<div/>");
				var _lnk = $("<a/>");
				_lnk.attr("href", this.type.getItemLink(data));
				_lnk.text(data.name);
				if (data.expansion){
					var s = $("<span/>").addClass( data.expansion == 1 ? "bc-icon" : "wotlk-icon");
					_lnk.appendTo(s);
					s.appendTo(m)
				}else{
					_lnk.appendTo(m);
				}				
				if (data.exotic){
					m.css("position", "relative");
					var extoicdiv = $("<div/>").addClass("small q0").css({
						"font-style" : "italic",
						"position" : "absolute",
						"right" : "3px",
						"bottom": 0
					}).text("特殊").appendTo(m);
				}
				m.appendTo(container);
			},
			getVisibleText:function(data){
				var str = data.name;
				if (data.expansion == 1){
					str += " bc";
				}else if(data.expansion == 2){
					str += " wotlk wrath";
				}
				if (data.exotic){
					str += " 特殊";
				}
				return str;
			}
		},
		{
			id : "level",
			name: "等级",
			type: "range",
			getMinValue: function(data){
				return data.minlevel;
			},
			getMaxValue: function(data){
				return data.maxlevel;
			},
			compute:function(data, container){
				if (data.minlevel > 0 && data.maxlevel > 0){
					if (data.minlevel != data.maxlevel){
						return data.minlevel + "-" + data.maxlevel;
					}else{
						return data.minlevel;
					}
				}else{
					return -1;
				}
			},
			sortFunc: function(data1, data2, sid){
				if (sid > 0){
					return strcmp(data1.minlevel, data2.minlevel) || strcmp(data1.maxlevel, data2.maxlevel);
				}else{
					return strcmp(data1.maxlevel, data2.maxlevel) || strcmp(data1.minlevel, data2.minlevel);
				}
			}
		},
		{
			id: "damage",
			name: "伤害",
			value: "damage",
			compute: function(data, container){
				container.append(this.type.getStatPct(data.damage));
			}
		},
		{
			id: "armor",
			name: "护甲",
			value: "armor",
			compute: function(data, container){
				container.append(this.type.getStatPct(data.armor));
			}
		},
		{
			id: "health",
			name: "生命值",
			value: "health",
			compute: function(data, container){
				container.append(this.type.getStatPct(data.health));
			}
		},
		{
			id: "abilities",
			name: "技能",
			type: "text",
			hidden: true,
			compute: function(data, container){
				if (!data.spells){return "";}
				if (data.spells.length > 0){
					container.css("padding", 0);
					Editor.createCenteredIcons(data.spells, container, "", 1);
				}
			},
			getValue:function(data){
				if (!data.spells){return "";}
				if (data.spells.length > 0){
					var str = "";
					for (var d = 0; d < data.spells.length; ++d){
						if (data.spells[d]){
							str += wsSpells[data.spells[d]]["name"];
						}
					}
					return str;
				}
			},
			sortFunc: function(data1, data2){
				if (!data1.spells || !data2.spells){return 0};
				return strcmp(data1.spellCount, data2.spellCount) || strcmp(data1.spells, data2.spells);
			}
		},
		{
			id: "diet",
			name: "食物",
			type: "text",
			compute: function(data, container){
				if (container){
					container.addClass("small");
				}
				var index = 0, s = "";
				for (var k in pet_foods){
					if (data.diet & k){
						if (index ++ > 0){
							s += ", ";
						}
						s += pet_foods[k];
					}
				}
				return s;
			},
			sortFunc:function(data1, data2){
				return strcmp(data1.foodCount, data2.foodCount) || Editor.assocArrCmp(data1.diet, data2.diet, pet_foods)
			}
		},
		{
			id: "type",
			name: "类型",
			type: "text",
			compute: function(data, container){
				if (data.type != null){
					container.addClass("small q1")
					var _lnk = $("<a/>").attr("href", "/pet/index.php?type="+data.type).text(pet_types[data.type]).appendTo(container);
				}
			},
			getVisibleText: function(data){
				if (data.type != null){
					return pet_types[data.type];
				}
			},
			sortFunc: function(data1, data2, sid){
				return strcmp(pet_types[data1.type], pet_types[data2.type]);
			}
		}
		],
		getItemLink: function(data){
			return "/pet/#";
		},
		getStatPct: function(data){
			var n = $("<span/>");
			if (!isNaN(data) && data > 0){
				n.addClass("q2")
				n.text("+"+data+"%");
			}else{
				if (!isNaN(data) && data < 0) {
					n.addClass("q10")
					n.text(data+"%");
				}
			}
			return n
		}
	},
	comment: {
		mode: 2,
		nItemsPerPage: 40,
		columns: [{
            value: "number"
        },
        {
            value: "id"
        },
        {
            value: "rating"
        }],
		compute: function(data, container){
			container.addClass("comment");
			var uid = parseInt(ws_user.uid);
			var isAdmin = (ws_user.roles & 26) != 0;//登录用户是否为管理员
			var nukePost = data.rating < 0 || data.purged || data.deleted
			var canEdit = data.uid == uid || isAdmin;//判断当前评论是否为自己的或者是管理员
			var canDelete = canEdit && (data.deleted == 0);//能否删除
			//判断能否评分
			var canRating = data.purged == 0 && data.deleted == 0 && uid && data.uid != uid && in_array(uid, data.raters, true, function(obj){return obj[0]}) == -1;
			data.ratable = canRating;
			var canDetach = canEdit && data.replyTo != data.id;//能否分割
			
			if (data.indent) {
				container.addClass("comment-indent");
			}
			
			var cheader = $("<div />"), cbody = $("<div />"), clink = $("<div />");
			data.divHeader = cheader;
			data.divBody = cbody;
			data.divLinks = clink;
			
			/*
			 * 头部
			 */			
			cheader.addClass("comment-header");
			//评分,  + -
			//rating
			var rating = $("<div />").appendTo(cheader).addClass("comment-rating");
			var $ratext = $("<b/>").appendTo(rating);
			$ratext.append("等级: ");
			var $s = $("<span />").appendTo($ratext)
			$s.append(((data.rating > 0) ? "+" : "") + data.rating);
			rating.append(" ");			
			var $s = $("<span />").appendTo(rating);// + -
			var stamp, peak;
			peak = $("<a />").text("[顶]").appendTo($s)
			rating.append(" ");
			stamp = $("<a />").text("[踩]").appendTo($s)
			
			if (uid > 0) {
				peak.attr("href", "javascript:;")
				stamp.attr("href", "javascript:;")
				peak.bind("click", function(){
					Editor.updateRate.bindContext(peak, data, 1)();
				});
				stamp.bind("click", function(){
					Editor.updateRate.bindContext(stamp, data, -1)();
				});
			}else{
				peak.attr("href", "/login.php");
				stamp.attr("href", "/login.php");
			}
			if (canRating){
				$s.show()
			}else{
				$s.hide()
			}
			
			//用户名, 日期, 版本
			cheader.append('<span class="q">'+data.user+"</span>");
			cheader.append(" ");
			$("<span />").addClass("q0").text("发表于"+data.date).appendTo(cheader)
			cheader.append(" ("+get_wowpatch[data.patch]+")");
			
			//文章内容			
			cbody.addClass("comment-body");
			cbody.addClass(Editor.getColor(data))
			if (data.indent){
				cbody.addClass("comment-body-indent");
			}
			cbody.html(Markup.toHtml(data.body, {mode: Markup.MODE_COMMENT, roles: data.roles}));
			
			//lastedit
			var lastedit = $("<div />").addClass("comment-lastedit")
			data.divLastEdit = lastedit;
			$("<span />").appendTo(lastedit)
			lastedit.append(" 最后编辑于 ");
			$("<span />").appendTo(lastedit)
			Editor.updateLastEdit(data);			
			if (nukePost){
				lastedit.hide();
			}
						
			//links
			clink.addClass("comment-links");
			//edit
			if (canEdit){
				var editspan = $("<span />").appendTo(clink);
				var eidtlnk = $("<a />").appendTo(editspan).text("编辑").attr("href", "javascript:;");
				eidtlnk.bind("click", function(){
					Editor.quickEdit(data, 0);
				})
				editspan.append("|");
			}
			//删除
			if (canDelete){
				var delspan = $("<span />").appendTo(clink);
				var dellnk = $("<a />").appendTo(delspan).text("删除").attr("href", "javascript:;");
				dellnk.bind("click", Editor.postDelete.bindContext(this, data));
				delspan.append("|");
			}
			//分离
			if (canDetach){
				//var detachspan = $("<span />").appendTo(clink);
				//var detachlnk = $("<a />").appendTo(detachspan).text("分离").attr("href", "javascript:;");
				//detachspan.append("|");
			}
			
			var reply = $("<a />").text("回复").appendTo(clink)
			if (uid > 0){
				reply.attr("href", "javascript:;");
				reply.bind("click", function(){
					Editor.replyPost(data)
				});
			}else{
				reply.attr("href", "/login.php");
			}
			
			if (nukePost){
				cbody.hide();
				clink.hide();
			}
			
			//append parent
			cheader.appendTo(container);
			cbody.appendTo(container);
			lastedit.appendTo(container)
			clink.appendTo(container);		
		},
		createNote: function(ntop){
			var note = $("<small />").appendTo(ntop);
			var lnk = $("<a/>").appendTo(note);
			if (ws_user.uid > 0){
				lnk.attr("href", "javascript:;").bind("click", function(){
					skip_addcomment();
				}).text("发表评论")
			}else{
				lnk.text("发表评论").attr("href", "/login.php");
			}
		},
		onNoData:function(parent){
			var div = $("<div/>").appendTo(parent).css({"padding": "1.5em 0", "text-align" : "center"});

			if (ws_user.uid > 0){
				div.append("<b>当前还没有评论！</b><br/>赶快");
				$("<a/>").attr("href", "javascript:;").text("发表第一篇评论！").bind("click", function(){
					skip_addcomment()
				}).appendTo(div);
			}else{
				div.html("<b>当前还没有评论！</b><br/>你还没有登录, 请<a href=\"/login.php\">登录</a>发表评论。");
			}
		},
		onBeforeCreate:function(){
			
		},
		onAfterCreate:function(){
			
		}
	}
}

var Facebox = new function(){
	var options = {}, haveContainer, faceoverlay, faceouter, faceinner, currId, divs = {};
	function bindevent(){
		registerEvent(faceoverlay[0], "click", hidedivs);
		registerEvent(document, $.browser.opera ? "keypress" : "keydown", keylistener);
		registerEvent(window, "resize", setHeight);
		if ($.browser.msie6){
			registerEvent(window, "scroll", msie6fixable);
		}
	}
	function unbindevent(){
		unregisterEvent(faceoverlay[0], "click", hidedivs);
		unregisterEvent(document, $.browser.opera ? "keypress" : "keydown", keylistener);
		unregisterEvent(window, "resize", setHeight);
		if ($.browser.msie6){
			unregisterEvent(window, "scroll", msie6fixable);
		}
	};
	function createFaceContainer(){
		if (haveContainer){
			return
		}
		haveContainer = 1;
		var layers = $("#layers");
		faceoverlay = $("<div />").addClass("facebox-overlay").appendTo(layers);
		faceouter = $("<div />").addClass("facebox-outer").appendTo(layers);
		faceinner = $("<div />").addClass("facebox-inner").appendTo(faceouter);
		faceoverlay.hide();
		faceouter.hide();
	};
	//设定高度
	function setHeight(height){
		if (height != 1234){
			if (options.onResize){
				options.onResize();
			}
		}
		faceoverlay.height($(document).height());
		if ($.browser.msie6){
			msie6fixable()
		}
	};
	//opera
	function keylistener(e){
		e = getInfoFromEvent(e);
		if (e.keyCode == 27){
			hidedivs();
		}
	};
	//msie6
	function msie6fixable(){
		var sheight = $(window).scrollTop(), wheight = $(window).height();
		faceouter.css("top", (sheight + wheight/2)+"px");
	};
	//隐藏所有
	function hidedivs(){
		unbindevent();
		if (options.onHide){
			options.onHide();
		}
		faceoverlay.hide();
		faceouter.hide();
		ws_enableScroll(true);
	};
	//显示所有div层
	function showdivs(){
		faceoverlay.show();
		faceouter.show();
		divs[currId].show();
	};
	this.setSize = function(w, h){
		faceinner.css({
			"visibility" : "hidden",
			"width" : w+"px",
			"height" : h + "px",
			"left" : -parseInt(w / 2) + "px",
			"top" : -parseInt(h / 2) + "px",
			"visibility" : "visible"
		});
	};
	//缺少一个参数
	this.show = function(id, cfg){
		options = cfg || {};
		createFaceContainer();
		bindevent();
		if (currId != id && divs[currId] != null){
			divs[currId].hide();
		}
		currId = id;
		
		var container, newdiv;
		if (divs[id] == null){
			newdiv = 1;
			container = $("<div />").appendTo(faceinner);
			divs[id] = container;
		}else{
			container = divs[id];
		}
		if (options.onShow){
			//当前div层, 是否是新的div
			options.onShow(container, newdiv);
		}
		setHeight(1234);
		showdivs();
		ws_enableScroll(false);
	};
	this.reveal = function(){
		showdivs();
	};
	this.hide = function(){
		hidedivs();
	};
	this.isVisible = function(){
		return !faceoverlay.is(":hidden")
	}
}


//icon图标操作方法
/*
 * <div class="icon">
 * 	<ins>
 *  	<del>
 *  	</del>
 *  </ins>
 * </div>
 */
var Icon = {
	sizes: ["small", "medium", "large"],
	sizes2: [18, 36, 56],
	premiumOffsets : [
		[-56, -36],
		[-56, 0],
		[0, 0]
	],
	create: function(iconName, iconSize, tooltip, url, topnum, stack){//创建icon * * 底部堆叠 上部堆叠
		var $icon = $("<div />");//创建一个icon div层
		if (iconSize == null){
			iconSize = 1;
		}
		$icon.addClass("icon"+Icon.sizes[iconSize]);//为icon增加样式
		var $ins = $("<ins/>").appendTo($icon);
		var $del = $("<del/>").appendTo($icon);
		Icon.setTexture($icon, iconSize, iconName);
		
		if (url){
			var $url = $("<a/>").appendTo($icon);
			$url.attr("href", url);
		}else{
			if ($.browser.opera){
				$icon.click(Icon.onClick);
			}else{
				$icon.dblclick(Icon.onDoubleClick)//设置双击
			}			
		}
		Icon.setNumQty($icon, topnum, stack);
		return $icon;
	},
	setTexture: function(icondiv, iconSize, iconName){//icon主层, 尺寸, icon名
		if (!iconName){return};
		//找到ins
		var texture = icondiv.find("ins");
		//如果包含 /
		if (iconName.indexOf("/") !=  -1){
			texture.css({"background-image": "url("+iconName+")"})
		}else{
			var iconUrl = "url("+imgdomain+"/images/icons/"+Icon.sizes[iconSize]+"/"+iconName.toLowerCase()+".jpg)";
			texture.css({"background-image": iconUrl});
		}
		Icon.moveTexture(icondiv, iconSize, 0, 0);
	},
	moveTexture: function(icondiv, iconSize, posX, posY){
		var texture = icondiv.find("ins");
		if (posX || posY){
			texture.css({"background-position": ((-posX*Icon.sizes2[iconSize])+"px "+(-posY*Icon.sizes2[iconSize])+"px")});
		}else{
			if (texture.css("background-position")){
				texture.css({"background-position": ""});
			}
		}
	},
	setNumQty : function(target, stack, topnum){
		//clear glow;
		//底部的堆积数量
		if (stack !=null && ((stack >1 && stack < 2147483647) || stack.length)){
			var $glow = createGlow(stack, "q1");
			$glow.css({
				"right": 0,
				"bottom": 0,
				"position": "absolute"
			})
			$glow.appendTo(target);			
		}		
		
		//顶部显示(1)
		if (topnum!=null && topnum > 0){
			var $glow = createGlow("("+topnum+")", "q");
			$glow.css({
				"left": 0,
				"top": 0,
				"position": "absolute"
			})
			$glow.appendTo(target);
		}		
	},
	//return element
	getLink: function($icon){
		return $icon.find("a")[0];
	},
	onDoubleClick: function(){
		var childs = $(this).children();
		if (childs.length <= 0){return}
		firstChild = childs[0]
		if (firstChild){
			var $imgurl = $(firstChild).css("background-image");
			if ($imgurl.length && $imgurl.indexOf("url("+imgdomain)==0){
				var first = $imgurl.lastIndexOf("/");
				var last = $imgurl.indexOf(".jpg")
				if (first != -1 && last!=-1){
					prompt("", $imgurl.substring(first+1, last));
				}
			}
		}
	},
	onClick:function(){
		if (this.lastClick){
			var t = new Date().getTime();
			if (t - this.lastClick < 400){
				Icon.onDoubleClick.bindContext(this)();
				this.lastClick = null;
			}else{
				this.lastClick = t
			}
		}else{
			this.lastClick = new Date().getTime();
		}
	}
}

//Tooltip操作方法
var Tooltip = {
	create: function(html){
		var $root = $("<div class=\"tooltip\" />");
		
		//$root.addClass("tooltip");
		var $table = $("<table/>").appendTo($root);
		var $tbody = $("<tbody/>").appendTo($table);
		//top tr
		var $toptr = $("<tr/>").appendTo($tbody);
		var $tleft = $("<td/>").appendTo($toptr);
		var $tright = $("<th/>").appendTo($toptr).css("background-position", "top right");
		if (html){
			$tleft.html(html);
		}
		//bottom tr
		var $bottomtr = $("<tr/>").appendTo($tbody);
		var $bleft = $("<th/>").appendTo($bottomtr).css("background-position", "bottom left");
		var $bright = $("<th/>").appendTo($bottomtr).css("background-position", "bottom right");
		
		Tooltip.icon = $("<p/>").css("visibility", "hidden")
		.prepend($("<div />"))
		.appendTo($root);
		
		return $root;
	},
	fix: function(eid, isShrink, isVisible){//传入已经过$(div)的元素id, 是否需要缩小, 是否可见
		var $table = eid.find("table")[0];
		var $td = eid.find("td")[0];
		var tdnodes = $td.childNodes;
		if (tdnodes.length >= 2 && tdnodes[0].nodeName == "TABLE" && tdnodes[1].nodeName == "TABLE"){
			$(tdnodes[0]).css("white-space", "nowrap");
			var adjustWidth;
			//调整宽度尺寸
			if ($(tdnodes[1]).width() > 300){
				adjustWidth = Math.max(300, $(tdnodes[0]).width()) + 20
			}else{
				adjustWidth = Math.max($(tdnodes[0]).width(), $(tdnodes[1]).width())+20;
			}
			if (adjustWidth > 20){
				eid.css("width", adjustWidth+"px");//调整tooltip整体宽度
				$(tdnodes[0]).css("width", "100%");//调整wrap层的宽度 比如  技能名  等级
				
				if (!isShrink && eid.height()>document.body.clientHeight){
					eid.addClass("shrink");
				}
			}
		}
		if (isVisible){
			eid.css("visibility", "visible")
		}
	},
	fixSafe:function(eid, isShrink, isVisible){//传入已经过$(div)的元素id, 修正参数
		if ($.browser.msie){
			setTimeout(Tooltip.fix.bindContext(this, eid, isShrink, isVisible), 1);
		}else{
			Tooltip.fix(eid, isShrink, isVisible);
		}
	},
	append: function($root, html){//传入经过$的元素id, html文本
		var $tip = Tooltip.create(html).appendTo($root);
		Tooltip.fixSafe($tip, 1, 1);
	},
	prepare:function(){
		if (Tooltip.tooltip){
			return
		}
		var $layers = $("#layers")//每个页面顶部必须写上<div id="layers"></div>
		var $tip = Tooltip.create();
		$tip.css({
			"position": "absolute",
			"left": "-2323px"
		});
		$tip.appendTo($layers);
		Tooltip.tooltip = $tip;
		Tooltip.TooltipTable = $tip.find("table")[0];
		Tooltip.TooltipTd = $tip.find("td")[0];
		if ($.browser.msie6){
			$tip = $("<iframe/>");
			$tip.attr({
				"src": "javascript:0;",
				"border": 0
			});
			$tip.appendTo($layers);
			Tooltip.iframe = $tip;		
		}
	},
	set:function(html){
		var $tip = Tooltip.tooltip;
		$tip.css({
			"width": "550px",
			"left": "-2323px",
			"top": "-2323px",
			"display": ""
		})
		$(Tooltip.TooltipTd).html(html);
		Tooltip.fix($tip, 0, 0);
	},
	moveTests:[[null, null], [null, false], [false, null], [false, false]],
	move:function(posX, posY, width, height, fixWidth, fixHeight){
		if (!Tooltip.TooltipTable){
			return
		}
		var $tip = Tooltip.tooltip, 
		tipWidth = Tooltip.TooltipTable.offsetWidth, 
		tipHeight = Tooltip.TooltipTable.offsetHeight;
		$tip.css("width", tipWidth+"px");//设置tip宽度
		var tipAttr, q;
		for (var g=0, len=Tooltip.moveTests.length; g<len; ++g){
			q = Tooltip.moveTests[g];
			tipAttr = Tooltip.moveTest(posX, posY, width, height, fixWidth, fixHeight, q[0], q[1]);
		}
		//left top visibility
		$tip.css({
			"left": tipAttr.posX+"px",
			"top": tipAttr.posY+"px",
			"visibility": "visible"
		});
		if ($.browser.msie6 && Tooltip.iframe){
			var $iframe = Tooltip.iframe;
			$iframe.css({
				"left": tipAttr.posX+"px",
				"top": tipAttr.posY+"px",
				"width": tipWidth+"px",
				"height": tipHeight+"px",
				"display": "",
				"visibility": "visible"
			});
		}
	},
	//abswidth 设定是否绝对位置
	//fixwidth fixHeight 为位置修正值
	moveTest: function(posX, posY, width, height, fixWidth, fixHeight, abswidth, absheight){
		var oldPosX = posX, 
			oldPosY = posY, 
			$tip=Tooltip.tooltip, 
			tipTblWidth = $(Tooltip.TooltipTable).width(), 
			tipTblHeight = $(Tooltip.TooltipTable).height(), 
			windowWidth = $(window).width(),
			windowHeight = $(window).height(), 
			scrollX = $(window).scrollLeft(),
			scrollY = $(window).scrollTop(),
			relwidth = scrollX + windowWidth,
			relheight = scrollY + windowHeight;
			
		if (abswidth == null){
			abswidth = (posX + width + tipTblWidth <= relwidth);
		}
		if (absheight == null){
			absheight = (posY - tipTblHeight >= relheight)
		}
		
		//目前先调整为当前状态
		//if (abswidth){ //true
			posX += width + fixWidth
		//}else{
		//	posX = Math.max(posX - tipTblWidth, scrollX) - fixWidth
		//}
		
		//if (absheight){ //true
			posY -= tipTblHeight + fixHeight
		//}else{
		//	posY += height + fixHeight;
		//}
		
		if (posX < scrollX){
			posX = scrollX;
		}else{
			if (posX + tipTblWidth > relwidth){
				posX = relwidth - tipTblWidth;
			}
		}
		
		if (posY < scrollY){
			posY = scrollY;
		}else{
			if (posY + tipTblHeight > relheight){
				posY = Math.max(scrollY, relheight - tipTblHeight);
			}
		}
		
		if (Tooltip.iconVisible){
			if (oldPosX >= posX - 48 && oldPosX <= posX && oldPosY >= posY-4 && oldPosY <= posY + 48){
				posY -= 48 - (oldPosY - posY);
			}
		}
		return {
			posX: posX,
			posY: posY,
			tipTblWidth: tipTblWidth,
			tipTblHeight: tipTblHeight
		}
	},
	show: function(that, html, fixWidth, fixHeight, className){
		if (Tooltip.disabled){
			return
		}
		if (!fixWidth || fixWidth< 1){
			fixWidth = 1;
		}		
		if (!fixHeight || fixHeight < 1){
			fixHeight = 1;
		}		
		if (className){
			html = '<span class="' + className + '">' + html + "</span>";
		}
		Tooltip.prepare();
		Tooltip.set(html);
		Tooltip.move(that.offset().left, that.offset().top, that.width(), that.height(), fixWidth, fixHeight);
	},
	//that = event
	showAtCursor: function(that, html, fixWidth, fixHeight, className){
		if (Tooltip.disabled){
			return
		}
		if (!fixWidth || fixWidth< 1){
			fixWidth = 1;
		}		
		if (!fixHeight || fixHeight < 1){
			fixHeight = 1;
		}		
		if (className){
			html = '<span class="' + className + '">' + html + "</span>";
		}
		that = getInfoFromEvent(that)
		var pos = getCursorPos(that)
		Tooltip.prepare();
		Tooltip.set(html);
		Tooltip.move(pos.x, pos.y, 0, 0, fixWidth, fixHeight);
	},
	showAtXY: function(html, posX, posY, fixWidth, fixHeight){
		if (Tooltip.disabled){
			return
		}
		Tooltip.prepare();
		Tooltip.set(html);
		Tooltip.move(posX, posY, 0, 0, fixWidth, fixHeight);
	},
	//that = event
	cursorUpdate: function(that, fixWidth, fixHeight){
		if (Tooltip.disabled || !Tooltip.tooltip){
			return
		}
		if (!fixWidth || fixWidth < 10){
			fixWidth = 10;
		}
		if (!fixHeight || fixHeight < 10){
			fixHeight = 10;
		}
		that = getInfoFromEvent(that)
		var pos = getCursorPos(that)
		Tooltip.move(pos.x, pos.y, 0, 0, fixWidth, fixHeight);
	},
	hide: function(){
		if (Tooltip.tooltip){
			var $tip = Tooltip.tooltip;
			$tip.css({
				"display": "none",
				"visibility": "hidden"
			});
			$(Tooltip.TooltipTable).removeClass();
			if ($.browser.msie6){
				$(Tooltip.iframe).css("display", "none")
			}
			Tooltip.setIcon(null)
		}
	},
	setIcon: function(iconname){
		Tooltip.prepare();
		var $icon = Tooltip.icon
		if (iconname){
			$icon.css({
				"background-image": "url("+imgdomain+"/images/icons/medium/"+iconname.toLowerCase()+".jpg)",
				"visibility": "visible"
			})
		}else{
			$icon.css({
				"background-image": "none",
				"visibility": "hidden"
			})
		}
		Tooltip.iconVisible = iconname ? 1: 0;
	}
}

function getIdFromTypeName(type){
	var list = getIdFromTypeName.list;
	return (list[type]?list[type]:-1)
}

getIdFromTypeName.list = {
	npc: 1,
    object: 2,
    item: 3,
    itemset: 4,
    quest: 5,
    spell: 6,
    zone: 7,
    faction: 8,
    pet: 9,
    achievement: 10
}

var wsItems = {};
wsItems.add = function(id, itemInfo){
	if (wsItems[id] != null){
		$.extend(wsItems[id], itemInfo)
	}else{
		wsItems[id] = itemInfo;
	}
}
wsItems.getIcon = function(id){
	if (wsItems[id] != null) {
        return wsItems[id].icon
    } else {
        return "inv_misc_questionmark"
    }
}
wsItems.createIcon = function(id, size, stack, top){
	return Icon.create(wsItems.getIcon(id), size, null, "/item/info.php?id="+id, stack, top);
}
//任务
var wsQuests = {}
//法术
var wsSpells = {}
wsSpells.add = function(){}
wsSpells.getIcon = function(id){
	if (wsSpells[id] != null){
		return wsSpells[id].icon
	}else{
		return "inv_misc_questionmark";
	}
}
wsSpells.createIcon = function(id, size, stack, top){
	return Icon.create(wsSpells.getIcon(id), size, null, "/spell/info.php?id="+id, stack, top);
}
//成就
var wsAchievements = {};
wsAchievements.getIcon = function(id){
	if (wsAchievements[id] != null){
		if (wsAchievements[id].icon.length){
			return wsAchievements[id].icon
		}else{
			return "inv_misc_questionmark";
		}
		
	}else{
		return "inv_misc_questionmark";
	}
}
wsAchievements.createIcon = function(id, size, stack, top){
	return Icon.create(wsAchievements.getIcon(id), size, null, "/achievement/info.php?id="+id, stack, top);
}
//声望
var wsFactions = {};
//pets
var wsPets = {};
//obj
var wsObjects = {};
//
var wsNpcs = {}; 

/*
 * 鼠标即时提示
 */
var WowshellPower = new function(){
	var currTypeId, currDataSlice, currExtraInfo, currDomain, $target, isSetIcon = 0, cursorX, cursorY, fixCursorX = 15, fixCursorY = 15, itemExtraInfo, domain;
	var _profiles = {}, _npcs = {}, _objects = {};
	var methods = {
		1: [_npcs, "npc"],
		2: [_objects, "object"],
		3: [wsItems, "item"],
		5: [wsQuests, "quest"],
		6: [wsSpells, "spell"],
		10: [wsAchievements, "achievement"],
		100: [_profiles, "profile"]
	}
	/*
	 * 将整个网页中的mouseover event进行监听
	 * 调用EventHandler处理事件函数
	 */
	function addListenEvent(){
		registerEvent(document, "mouseover", EventHandler);
	};
	function getCursorXY(e){
		var curpos = getCursorPos(e);
		cursorX = curpos.x;
		cursorY = curpos.y;
	}
	/*
	 * Mouseover事件处理函数
	 * 进行初步的filter
	 * @parma: e=>event
	 */
	function EventHandler(e){
		e = getInfoFromEvent(e);
		var t = e._target;
		var j = 0;
		while (t != null && j<3 && showTooltipEvent(t, e) == -2323){
			t = t.parentNode;
			++j
		}
	};
	/*
	 * tooltip event management
	 * target link
	 * e event
	 * 
	 * TODO: 后面会加入带有珠宝数据的分析 暂时只实现基本功能
	 */
	function showTooltipEvent(target, e){
		if (target.nodeName != "A" && target.nodeName != "AREA"){
			return -2323
		}
		if (!target.href.length){
			return;
		}
		if (target.rel.indexOf("np") != -1){
			return;
		}
		
		/*
		 * 分析当前的链接 提取类型以及id
		 * 类型: item, quest, spell, achievement
		 */
		var headInfo,//从url中获取的相关信息 其中包含语言版本,类别以及id 
		urlHeader, urltype, urlId;//url头(比如www,db,twdb)  urltype(包括spell, item, quest, achievement) urlid 相对应的id
		var tmpRelInfo = {};
		itemExtraInfo = tmpRelInfo;
		/*
		 * 匹配语句
		 * 类型
		 * 数据
		 */
		var getRelInfo = function(exinfo, extype, exval){
			if (extype == "buff" || extype == "sock"){
				tmpRelInfo[extype] = true;
			}else{
				if (extype=="rand" || extype=="ench" || extype=="lvl" || extype=="c"){
					tmpRelInfo[extype] = parseInt(exval);
				}else{
					if (extype=="gems" || extype=="pcs"){
						tmpRelInfo[extype] = exval.split(":");
					}else{
						if (extype == "domin" || extype=="who"){
							tmpRelInfo[extype]=exval;
						}else{
							if (extype=="when"){
								tmpRelInfo[extype] = new Date(parseInt(exval));
							}
						}
					}
				}
			}
		}
		
		urltype = 3, urlId =4
		if (target.href.indexOf("http://") == 0){
			urlHeader = 1;
			headInfo = target.href.match(/http:\/\/(.+?)?\.?(wowshell|sa20)\.com\/(item|quest|spell|achievement)\/info\.?php\?id=([0-9]+)/);
		}else{
			headInfo = target.href.match(/()()\/(item|quest|spell|achievement)\/info\.?php\?id=([0-9]+)/);
			if (headInfo == null){
				headInfo = target.href.match(/()()\/(profile)\/info\.?php\?id=([^&#]+)/);
			}
		};
		
		if (headInfo == null && target.rel){
			urlHeader = 0
			urltype = 1
			urlId = 3
		}
		
		/*
		 * rel:
		 * gems
		 * ench
		 * pcs
		 * lvl
		 * rand
		 */		
		if (target.rel){
			target.rel.replace(/([a-zA-Z]+)=?([a-zA-Z0-9:-]*)/g, getRelInfo);
			if (tmpRelInfo.gems && tmpRelInfo.gems.length > 0){
				var gemNum;
				for (gemNum=Math.min(3, tmpRelInfo.gems.length-1); gemNum>=0; --gemNum){
					if (parseInt(tmpRelInfo.gems[gemNum])){
						break;
					}
				}
				++gemNum;
				if (gemNum == 0){
					delete tmpRelInfo.gems;
				}else{
					if (gemNum < tmpRelInfo.gems.length){
						tmpRelInfo.gems = tmpRelInfo.gems.slice(0, gemNum);
					}
				}
			}
		}
		
		if (headInfo){
			domain = "www";
			$target = $(target);
			isSetIcon = (target.parentNode.className.indexOf("icon") == 0) ? 1: 0
			
			//urltype urlId
			if (target.href.indexOf("#") != -1 && document.location.href.indexOf(headInfo[urltype]+"/info.php?id="+headInfo[urlId]) != -1){
				return;
			}
			
			if (!target.onmouseout){
				if (isSetIcon == 0){
					$target.mousemove(tipMousemove)
				}
				$target.mouseout(hideTooltip)
			}
			
			//获取鼠标当前位置
			getCursorXY(e)
			//typeid, url, gem/ench info
			LoadTooltip(getIdFromTypeName(headInfo[urltype]), headInfo[urlId], tmpRelInfo, domain);
		}
	}
	function hideTooltip(){
		currTypeId = null;
		$target = null;
		Tooltip.hide();
	}
	function tipMousemove(e){
		e = getInfoFromEvent(e);
		getCursorXY(e);
		Tooltip.move(cursorX, cursorY, 0, 0, fixCursorX, fixCursorY);
	}
	function methodStatus(typeid, extraDataSlice, domain){
		var method = methods[typeid][0]
		if (method[extraDataSlice] == null){
			method[extraDataSlice] = {}
		}
		if (method[extraDataSlice].status == null){
			method[extraDataSlice].status = {}
		}
		if (method[extraDataSlice].status[domain] == null){
			method[extraDataSlice].status[domain] = 0
		}
	};
	/*
	 * 0 未加载
	 * 1 正在加载
	 * 2 加载失败
	 * 3 buff/tooltip 3为同时显示buff和tooltip部分
	 * 4 获取成功
	 */
	function LoadTooltip(typeid, id, extraInfo, domain){
		if (!extraInfo){
			extraInfo = {};
		}
		var extraDataSlice = editExtraData(id, extraInfo);
		//把当前值赋予到全局变量中
		currTypeId = typeid;
		currDataSlice = extraDataSlice;
		currExtraInfo = extraInfo;
		currDomain = domain
		/*******/
		methodStatus(typeid, extraDataSlice, domain);
		var method = methods[typeid][0];
		if (method[extraDataSlice].status[domain] == 4 || method[extraDataSlice].status[domain] == 3){
			setTooltip(method[extraDataSlice][isShowBuff()], method[extraDataSlice]["icon"]);
		}else{
			if (method[extraDataSlice].status[domain] == 1){
				setTooltip("数据载入中...")
			}else{
				//数据通过ajax获取之后 保存在method[id]下
				ajaxGetData(typeid, id, domain, null, extraInfo);
			}
		};
	}
	function isShowBuff(){
		return (itemExtraInfo.buff ? "buff" : "tooltip");
	}
	function ajaxGetData(typeid, id, domain, timer, extraInfo){
		var extraDataSlice = editExtraData(id, extraInfo);

		var method = methods[typeid][0];
		if (method[extraDataSlice].status[domain] != 0 && method[extraDataSlice].status[domain] != 2){
			return;
		}
		method[extraDataSlice].status[domain] = 1;
		if (!timer){
			method[extraDataSlice].timer = setTimeout(function(){
				showLoadingTip.apply(this, [typeid, extraDataSlice, domain])
			}, 333);
		}
		//综合url
		var extraurl = "";
		for (var extype in extraInfo){
			if (extype != "ench" && extype!="gems" && extype != "rand" && extype != "sock"){
				continue;
			}else{
				extraurl += "&comid="+extraDataSlice;
			}
			if (typeof extraInfo[extype] == "object"){
				extraurl += "&" + extype + "=" + extraInfo[extype].join(":");
			}else{
				if (extype == "sock"){
					extraurl += "&sock";
				}else{
					extraurl += "&" + extype + "=" + extraInfo[extype];
				}
			}
		}
		var nurl = sitepath+"/ajax/tooltip.php?type="+methods[typeid][1]+"&id="+id + extraurl;
		$.ajax({
			url: nurl,
			type: "GET",
			dataType: "script",
			success: function(data, textStatus){
			}
		});
	};
	//加载数据tip
	function showLoadingTip(typeid, extraDataSlice, domain){
		if (currTypeId == typeid && currDataSlice == extraDataSlice && currDomain == domain )
		{
			setTooltip("数据载入中...");
			var method = methods[typeid][0];
			method[extraDataSlice].timer = setTimeout(function(){
				ShowResponseTip.apply(this, [typeid, extraDataSlice, domain])
			}, 3850);
		}
	}
	//加载超时
	function ShowResponseTip(typeid, extraDataSlice, domain){
		var method = methods[typeid][0];
		method[extraDataSlice].status[domain] = 2;
		if (currTypeId == typeid && currDataSlice == extraDataSlice && currDomain == domain ){
			setTooltip("数据加载超时")
		}
	}
	function setTooltip(html, icon){
		if (!html){
			html = "加载失败:(";
			icon = "inv_misc_questionmark";
		}else{
			if (itemExtraInfo != null){
				if (itemExtraInfo.pcs && itemExtraInfo.pcs.length){
					
				}
				if (itemExtraInfo.c){
					
				}
				if (itemExtraInfo.lvl){
					
				}
				if (itemExtraInfo.who && itemExtraInfo.when){}
			}
		}
		if (isSetIcon == 1) {
			Tooltip.setIcon(null)
			Tooltip.show($target, html)
		}else{
			Tooltip.setIcon(icon)
			Tooltip.showAtXY(html, cursorX, cursorY, fixCursorX, fixCursorY);
		}
	}
	function editExtraData(id, extraInfo){
		return id + (extraInfo.rand ? "r" + extraInfo.rand : "") + (extraInfo.ench ? "e" + extraInfo.ench : "") + (extraInfo.gems ? "g" + extraInfo.gems.join(","): "") + (extraInfo.sock ? "s" : "");
	}
	
	this.register = function(type, id, localid, tip){
		var typeid = getIdFromTypeName(type);
		var method = methods[typeid][0];
		var domain = "www";
		if (method[id].timer){
			clearTimeout(method[id].timer);
			method[id].timer = null;
		}
		$.extend(method[id], tip);
		if (method[id].status[domain] == 1){
			if (method[id][isShowBuff()]){
				method[id].status[domain] = 3
			}else{
				method[id].status[domain] = 4
			}
		}
		if (currTypeId == typeid && currDataSlice == id && currDomain == domain ){
			setTooltip(method[id][isShowBuff()], method[id]["icon"])
		}
	}
	this.registerNpc = function(id, localid, tip){
		//this.register("npc", id, localid, tip);
	}
	this.registerObject = function(id, localid, tip){
		//this.register("object", id, localid, tip);
	}
	this.registerItem = function(itemid, localid, tip){
		this.register("item", itemid, localid, tip);
	}
	this.registerAchievement = function(id, local, tip){
		this.register("achievement", id, local, tip);
	}
	this.registerQuest = function(id, local, tip){
		this.register("quest", id, local, tip);
	}
	this.registerSpell = function(id, local, tip){
		this.register("spell", id, local, tip);
	}
	this.registerProfile = function(id, local, tip){
		//this.register("profile", id, local, tip);
	}	
	this.request = function(){
		
	}
	this.requestItem = function(){
		
	}
	this.requestSpell = function(){}
	this.getStatus = function(){}
	this.getItemStatus = function(){
	}
	this.getSpellStatus = function(){}
	addListenEvent();
}

var $Wow123Power = WowshellPower;//为了适合老的数据库, 重新指向函数名



/**
 * Cookie
 * options参数
 *  @expires 周期
 *  @path 作用域路径
 *  @domain 域名
 *  @secure 是否使用安全方式
 *  
 *  @option Number|Date expires
 *  @option String path
 *  @option String domain
 *  @option Boolean secure
 *  
 *  getCookie $.cookie(name)
 *  deleteCookie
 *  setCookie $.cookie(name, value, options)
 */
jQuery.cookie = function(name, value, options){
	if (typeof value != "undefined"){//set
		options = options || {};
		if (value === null){//del
			value = '';
			options = $.extend({}, options);
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)){
			var date;
			if (typeof options.expires == 'number'){
				date = new Date();
				date.setDate(date.getDate + expires);
			}else{
				date = options.expires
			}
			expires = '; expires='+date.toUTCString();
		}
		var path = options.path ? '; path='+(options.path) : "";
		var domain = options.domain ? "; domain="+(options.domain) : "";
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	}else{//get
		var cookieValue = null;
		if (document.cookie && document.cookie != ''){
			var cookies = document.cookie.split(";");//array
			for (var c=0, len = cookies.length; c < len; ++c){
				var cookie = trim(cookies[c]);
				if (cookie.substring(0, name.length+1) == (name+"=")){
					cookieValue = decodeURIComponent(cookie.substring(name.length+1));
					break;
				}
			}
		}
		return cookieValue;
	}
}

/**
 * Dragger
 */
jQuery.Dragger = new function(){
	var pos = {}, offset = {}, parent, new_parent;
	function _mouseCapture(e){
		e = getInfoFromEvent(e);
		if (this._handle) {
			var etarget = e._target;
			var isIncludeHandle = false;
			(this._handle).find("*").andSelf().each(function(){
				if (etarget == this){
					isIncludeHandle = true;
				}
			})
			if (!isIncludeHandle){
				return false;
			}
		}
		parent = this;
		pos = getCursorPos(e);
		//register
		registerEvent(document, "mousemove", _mouseStart);
		registerEvent(document, "mouseup", _mouseStop);
		if (parent.onClick){
			parent.onClick(e, parent);
		}
		return false;
	}
	//start move
	function _mouseStart(e){
		e = getInfoFromEvent(e);
		var trackpos = getCursorPos(e);
		if (parent) {
			if (Math.abs(trackpos.x - pos.x) > 5 || Math.abs(trackpos.y - pos.y) > 5) {
				_mouseDrag(e, parent);
				parent = null;
			}
		}
		if (!new_parent){
			return false;
		}
		var pOffset = _generatePosition($(new_parent)), 
			x = trackpos.x - pos.x, 
			y = trackpos.y - pos.y;
		x = Math.max(new_parent._bounds.x1 - offset.x, Math.min(new_parent._bounds.x2 - offset.x - (pOffset.x2 - pOffset.x1), x));
		y = Math.max(new_parent._bounds.y1 - offset.y, Math.min(new_parent._bounds.y2 - offset.y - (pOffset.y2 - pOffset.y1), y));
		_hideElement(x, y);		
		return false;
	}
	//stop
	function _mouseStop(e){
		e = getInfoFromEvent(e);
		parent = null;
		if (new_parent){
			_mouseDrop(e)
		}
	}
	//moving
	function _mouseDrag(e, parent){
		if (new_parent){
			_mouseDrop(e);
		}
		var elementOffset = $(parent).offset();
		offset.x = elementOffset.left;
		offset.y = elementOffset.top;
		if (parent._targets.length){
			new_parent = parent.cloneNode(true);
			new_parent._orig = parent;
			$(new_parent).appendTo($("#layers"));
			_hideElement(-2323, -2323);
		}else{
			new_parent = parent;
		}
		Tooltip.disabled = true;
		Tooltip.hide();
		var oldparent = new_parent._orig;
		if (oldparent.onDrag){
			oldparent.onDrag(e, new_parent, oldparent);
		}
		new_parent._bounds = _generatePosition(parent._container)
		$(new_parent).addClass("dragged");
	}
	function _mouseDrop(e){
		var trackingpos = getCursorPos(e), q = false;
		if (new_parent._orig && new_parent._orig._targets.length){			
			_resetPos();
			var t = {
				x1 : new_parent._x,
				x2 : new_parent._x + parseInt($(new_parent).outerWidth(true)),
				y1 : new_parent._y,
				y2 : new_parent._y + parseInt($(new_parent).outerHeight(true))
			}
			$(new_parent).empty();
			new_parent = new_parent._orig;
			for (var p=0, len = new_parent._targets.length; p < len; ++p){
				var target = new_parent._targets[p];				
				var targetOffset = _generatePosition(target);
				if (t.x2 >= targetOffset.x1 && t.x1 < targetOffset.x2 && t.y2 >= targetOffset.y1 && t.y1 < targetOffset.y2){
					q = true;
					if (new_parent.onDrop){						
						new_parent.onDrop(e, $(new_parent), target, (trackingpos.x >= targetOffset.x1 && trackingpos.x <= targetOffset.x2 && trackingpos.y >= targetOffset.y1 && trackingpos.y <= targetOffset.y2));
					}else{
						$(new_parent).appendTo(target)
					}
				}
			}
		}
		if (!q && new_parent.onDrop){
			new_parent.onDrop(e, $(new_parent), null);
		}
		
		unregisterEvent(document, "mousemove", _mouseStart);
		unregisterEvent(document, "mouseup", _mouseStop);
		Tooltip.disabled = false;
		new_parent.className = new_parent.className.replace(/dragged/, '');
		new_parent = null;
	}
	function _hideElement(x, y){
		$(new_parent).css({
			"position" : "absolute",
			"left" : offset.x + x + "px",
			"top": offset.y + y + "px"
		});
		new_parent._x = offset.x + x;
		new_parent._y = offset.y + y;
	}
	function _resetPos(){
		new_parent.style.top = "-2323px";
		new_parent.style.left = "-2323px";
	}
	function _generatePosition(parent){
		var parentOffset = parent.offset();
		return {
			x1 : parentOffset.left,
			x2 : parentOffset.left + parseInt(parent.outerWidth(true)),
			y1 : parentOffset.top,
			y2 : parentOffset.top + parseInt(parent.outerHeight(true))
		}
	}
	this.init = function(target, options){
		target.bind("mousedown", _mouseCapture);
		if (!target[0]._targets){
			target[0]._targets = [];
		}
		if (!target[0]._container){
			target[0]._container = $(document.body);
		}
		if (options != null){
			if (options.targets){
				for (var p=0, len = options.targets.length; p < len; ++p){
					target[0]._targets.push($(options.targets[p]))
				}
			}
			if (options.container){
				target[0]._container = options.container
			}
			if (options.onClick){
				target[0].onClick = options.onClick
			}
			if (options.onDrag){
				target[0].onDrag = options.onDrag
			}
			if (options.onDrop){
				target[0].onDrop = options.onDrop
			}
		}
	}
}
