/*中文UTF*/

var userAgent = navigator.userAgent.toLowerCase();
var is_webtv = userAgent.indexOf('webtv') != -1;
var is_kon = userAgent.indexOf('konqueror') != -1;
var is_mac = userAgent.indexOf('mac') != -1;
var is_saf = userAgent.indexOf('applewebkit') != -1 || navigator.vendor == 'Apple Computer, Inc.';
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko' && !is_saf) && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ns = userAgent.indexOf('compatible') == -1 && userAgent.indexOf('mozilla') != -1 && !is_opera && !is_webtv && !is_saf;
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera && !is_saf && !is_webtv) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
var body = document.compatMode == "CSS1Compat" ? document.documentElement : document.body;

var common = {
	maxZIndex: 100,
	tmpId: 0,
	evalscripts: new Array(),

	extend: function (destination,source){
		for(property in source){
			try {
				destination[property] = source[property];
			} catch(e){}
		};
		return destination;
	},
	
	isUndefined: function (variable) {
		return typeof variable == 'undefined' ? true : false;
	},
	
	getEvent: function (event) {
		if (is_ie) {
			return window.event;
		}
		if(!event){
			var func = this.getEvent.caller;
			while(func){
				event = func.arguments[0];
				if(event && event.constructor == Event){
					break ;
				}
				func = func.caller;
			}
		}
		return event;
	},

	each: function( obj, fn, args ) {
		if ( obj.length == undefined ){
			for ( var i in obj ) {
				fn.apply( obj[i], args || [i, obj[i]] );
			}
		} else {
			for ( var i = 0, ol = obj.length; i < ol; i++ ) {
				if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break;
			}
		}
		return obj;
	},
	
	

	pointerX: function (event){
		event = this.getEvent(event);
		return event.pageX || (event.clientX + body.scrollLeft);
	},
	
	pointerY: function (event){
		event = this.getEvent(event);
		return event.pageY || (event.clientY + body.scrollTop);
	},
	
	stop: function (event){
		event = this.getEvent(event);
		if (!event) return;
		if(is_ie){
			event.returnValue = false;
			event.cancelBubble = true;
		}else {
			event.preventDefault();
			event.stopPropagation();
		};
	},
	
	saveData: function (key, value, obj) {
		if(is_ie) {
			if (common.isUndefined(obj)) {
				obj = document.documentElement;
			}
			obj.addBehavior("#default#userdata");
			try {
				var oTimeNow = new Date();
				oTimeNow.setHours(oTimeNow.getHours() + 24);
				obj.expires = oTimeNow.toUTCString();
				obj.setAttribute('userdata', value);
				obj.save(key);
			} catch(e) {}
		} else if(window.sessionStorage) {
			try {
				sessionStorage.setItem(key, value);
			} catch(e) {}
		}
	},
	
	loadData: function (key, obj) {
		var value = '';
		if(is_ie) {
			if (common.isUndefined(obj)) {
				obj = document.documentElement;
			}
			obj.addBehavior("#default#userdata");
			try {
				obj.load(key);
				return obj.getAttribute("userdata");
			} catch(e) {}
		} else if(window.sessionStorage) {
			try {
				value = sessionStorage.getItem(k);
			} catch(e) {}
		}
		return value.toString();
	},
	
	eval: function (s) {
		if(s.indexOf('<script') == -1) return s;
		var p = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;
		var arr = new Array();
		while(arr = p.exec(s)) {
			this.append(arr[1], '', arr[2], arr[3]);
		}
		s = s.replace(p, '');
		p = /<script(.*?)>([^\x00]+?)<\/script>/ig;
		while(arr = p.exec(s)) {
			this.append('', arr[2], arr[1].indexOf('reload=') != -1);
		}
		return s;
	},
	
	append: function (src, text, reload, charset) {
		var id = this.hash(src + text);
		if(!reload && in_array(id, this.evalscripts)) return;
		if(reload && $(id)) {
			$(id).remove();
		}
	
		this.evalscripts.push(id);
		var scriptNode = document.createElement("script");
		scriptNode.type = "text/javascript";
		scriptNode.id = id;
		scriptNode.charset = charset;
		try {
			if(src) {
				scriptNode.src = src;
			} else if(text){
				scriptNode.text = text;
			}
			$('appendParent').appendChild(scriptNode);
		} catch(e) {}
	},
	
	hash: function (string, length) {
		var length = length ? length : 32;
		var start = 0;
		var i = 0;
		var result = '';
		filllen = length - string.length % length;
		for(i = 0; i < filllen; i++){
			string += "0";
		}
		while(start < string.length) {
			result = this.stringxor(result, string.substr(start, length));
			start += length;
		}
		return result;
	},
	
	stringxor: function (s1, s2) {
		var s = '';
		var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		var max = Math.max(s1.length, s2.length);
		for(var i=0; i<max; i++) {
			var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
			s += hash.charAt(k % 52);
		}
		return s;
	},
	
	/*
	设置下拉框的值
	*/
	setSelectValue: function (obj, v){
		for (var i=0; i < obj.length; i++){
			if (obj.options[i].value == v){
				obj.selectedIndex = i;
				return true;
			}
		}
		return false;
	}
};


/* 
*	为兼容旧版本的浏览器增加 Array 的 push 方法。 
*/ 

if(!Array.prototype.push) {
	Array.prototype.push = function () {
		var startLength = this.length;
		for(var i=0;i<arguments.length;i++) {
			this[startLength+i] = arguments[i];
		}
		return this.length;
	}
}

function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
				return i;
			}
		}
	}
	return false;
}

function trim(str) {
	return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}


function $(id, context) {
	var obj;
	context = context || document;
	switch(id){
		case "#html":
			obj = context.getElementsByTagName("html")[0];
			break ;
		case "#head":
			obj = context.getElementsByTagName("head")[0];
			break ;
		case "#body":
			obj = context.body;
			break ;
		default:
			obj = typeof(id) == 'string' ? $(context).getElementById(id) : id;
	}
	if(!obj){
		return null;
	}
	try{
		var objId = obj.getAttribute('id');
		if(!objId){
			obj.setAttribute("id", objId = ("mine-tmp-" + common.tmpId++));
		}
	}catch(e) {}
	
	if (!obj.isExtended) {
		common.extend(obj, common.extendHTMLElement);
	}
	
	return obj;
}

common.extendHTMLElement = {
	isExtended: function () {
		return true;
	},
	
	a : function() {
		return this.tagName;
	},
	
	/*
	查找当前对象下的指定内容
	>element			匹配此标签下的所有元素下的element
	.class				匹配具有此class值的所有元素
	[attribute=value]	匹配所有具有指定属性值的元素
	*/
	find: function(expr) {
		if (expr.match(/\W+/gi)) {
			var arr = [], t, re, m, cla = [], att = [], last;
			var a = />(\w*)/.exec(expr);	// 标签

			re = /\.(\w+)/gi;
			while(m = re.exec(expr)) {
				cla.push(m[1]);
			}
			expr = expr.replace(re, '');
			
			re = /\[(\w+)([\=!\*\^\$]*)(\w*)\]/gi;
			while(m = re.exec(expr)) {
				att.push([m[1], m[2], m[3]]);
			}

			var els = this.getElementsByTagName(a && a[1] ? a[1] : '*');
			for (i = 0; i < els.length; i++) {
				var r = cla || att ? 0 : 1;
				for (m = 0; m < cla.length; m++) {
					if ((' ' + els[i].className + ' ').indexOf(' ' + cla[m] + ' ') > -1) {
						r++;
						break;
					}
				}
				for (m = 0; m < att.length; m++) {
					var v = $(els[i]).get(att[m][0]);
					if (!v) {
						continue;
					}
					var mod = att[m][1];
					if (mod == '' && !!v ||
						mod == '=' && v == att[m][2] ||
						mod == '!=' && v != att[m][2] ||
						mod == '^=' && v && !v.indexOf(att[m][2]) ||
						mod == "$=" && v.substr(v.length - att[m][2].length) == att[m][2] ||
						mod == "*=" && v.indexOf(att[m][2]) > -1) {
							r++;
							break;
					}
				}
				if (r || (!cla.length && !att.length)) {
					arr.push(els[i]);
				}
			}
			return arr;
		} else {
			return document.getElementById(expr);
		}
	},
	
	/*
	*	获取样式
	*	return object {Class: className, Inline: style}
	*/
	getStyle: function() {
		var styles = new Object() ;
	
		if ( this.className.length > 0 ) {
			styles.Class = this.className ;
		}
	
		var sInlineStyle = this.style.cssText ;
	
		if ( sInlineStyle.length > 0 ) {
			styles.Inline = sInlineStyle ;
		}
	
		return styles ;
	},
	
	/*
	*	设置样式
	*	样式格式与获取方法的结果相同
	*/
	
	setStyle: function (styles) {
		this.className		= styles.Class || '' ;
		this.style.cssText	= styles.Inline || '' ;
	},
	
	/*
	*	清除样式
	*/
	clearStyle: function () {
		this.className = '';
		this.style.cssText = '' ;
	},
	
	
	/*
	*	tag:	
	*/
	create: function (tag, style, attrs, ext) {
		var obj = document.createElement(tag);
		if(style){
			common.extend(obj.style, style);
		}
		if(attrs){
			for(var k in attrs){
				obj.setAttribute(k, attrs[k]);
			}
		}
		this.appendChild(obj);
		if(ext){
			common.extend(obj, ext);
		}
		return $(obj);
	},
	
	drag: function () {
		var isDraging = false;
		var isMoved = false;
		var dragObjs = Array();
		if (!arguments.length) {
			dragObjs = [this];
		} else if (arguments.length == 1 && typeof arguments[0] == 'object' && !arguments[0].id) {
			dragObjs = arguments[0];
		} else {
			dragObjs = Array.prototype.slice.call(arguments, 0);
		}
		
		for (var i = 0; i < dragObjs.length; i++) {
			obj = $(dragObjs[i]);
			obj.on({'click': obj.upZIndex.bind(obj)});
			dragObjs[i] = obj;
		}
		
		this.style.cursor = 'move';
		
		this.downfunc = typeof this.onmousedown == 'function' ? this.onmousedown : null;
		this.onmousedown = function (event) {
			event = event || window.event;
			if(this.downfunc) this.downfunc();

			isDraging = true;
			isMoved = false;
			this.oldX = common.pointerX(event);
			this.oldY = common.pointerY(event);
			
			var box = $(this.id + '_box_');		//拖动时的虚线框
			if (!box) {
				//*
				var box = document.createElement('div');
				box.id = this.id + '_box_';
				box.className = 'dashedBox';
				document.body.appendChild(box);
				//*/
				//var box = $('#body').createElement('div', '', {id: this.id + '_box_'}, {className: 'dashedBox'});
			}
			
			//计算虚线框的大小及位置
			var oTop = null, oLeft = null, oRight = 0, oDown = 0;
			for(var i in dragObjs) {
				var obj = dragObjs[i];
				if (!obj) continue;
				
				if (!oTop || oTop > obj.offsetTop) {
					oTop = obj.offsetTop;
				}
				if (!oLeft || oLeft > obj.offsetLeft) {
					oLeft = obj.offsetLeft;
				}
				if (oRight < obj.offsetLeft + obj.offsetWidth) {
					oRight = obj.offsetLeft + obj.offsetWidth;
				}
				if (oDown < obj.offsetTop + obj.offsetHeight) {
					oDown = obj.offsetTop + obj.offsetHeight;
				}
				//	保存拖动对象的原始位置，以后计算可能会有偏差
				obj.primal = {left: obj.offsetLeft, top: obj.offsetTop};
			}
			
			
			with (box.style) {
				position = 'absolute';
				display = 'none';
				zIndex = ++common.maxZIndex;
				top = oTop + 'px';
				left = oLeft + 'px';
				width = oRight - oLeft + 'px';
				height = oDown - oTop + 'px';
				cursor = 'default';
			}

			/*
			*	保存拖动前虚线框的位置，以便和拖动后虚线框位而计算出拖动的距离
			*/
			box.primal = {left:oLeft, top:oTop};
			var o = this;
				
			if(o.setCapture)
				o.setCapture();
			else if(window.captureEvents)
				window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
			
			document.movefunc = typeof document.onmousemove == 'function' ? document.onmousemove : null;
			document.onmousemove = function (event) {
				if(isDraging){
					//if(document.movefunc) document.movefunc();
					event = event || window.event
					var X = common.pointerX(event);
					var Y = common.pointerY(event);
		
					box.style.display = '';
					box.style.left = box.offsetLeft + X - o.oldX + 'px';
					box.style.top = box.offsetTop + Y - o.oldY + 'px';
					
					o.oldX = X;
					o.oldY = Y;
					isMoved = true;
				}
			}
			
			document.upfunc = typeof document.onmouseup == 'function' ? document.onmouseup : null;
			document.onmouseup = function (event) {
				//if(document.upfunc) document.upfunc();
				if(o.releaseCapture)
					o.releaseCapture();
				else if(window.captureEvents)
					window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);

				isDraging = false;
				if (!isMoved) return;
				//根据虚线框的现位置和拖动前位置计算出拖动的距离
				var oLeft = box.offsetLeft - box.primal.left;
				var oTop = box.offsetTop - box.primal.top;
				
				for(var id in dragObjs) {
					var obj = dragObjs[id];
					if (!obj) continue;
					with (obj.style) {
						position = 'absolute';
						zIndex = ++common.maxZIndex;
						left = obj.primal.left + oLeft + 'px';
						top = obj.primal.top + oTop + 'px';
					}
				}
				box.style.display = 'none';
				document.onmousemove = document.movefunc;
				document.onmouseup = document.upfunc;
				document.ondragstart = null;
				document.onselectstart = null;
				document.onselect = null;
				isMoved = false;
			}
			
			document.ondragstart = common.stop.bind(common);
			document.onselectstart = common.stop.bind(common);
			document.onselect = common.stop.bind(common);

		}
	},
	
	getType : function() {
		if(this.tagName.toUpperCase() != "DIV") return HTMLUnknownElement;
			return HTMLDivElement;
	},
	
	getPos: function(){
		/*
		var pos = {
			width: parseInt(this.offsetWidth || this.style.width || this.clientWidth, 10),
			height: parseInt(this.offsetHeight || this.style.height || this.clientHeight, 10),
			left: parseInt(this.offsetLeft || this.style.left || this.clientLeft, 10),
			top: parseInt(this.offsetTop || this.style.top || this.clientTop, 10)
		};
		*/
		var obj = this;
		var left_offset = obj.offsetLeft;
		var top_offset = obj.offsetTop;
		while((obj = obj.offsetParent) != null) {
			left_offset += obj.offsetLeft;
			top_offset += obj.offsetTop;
		}
		return {
			width: parseInt(this.offsetWidth || this.style.width || this.clientWidth, 10),
			height: parseInt(this.offsetHeight || this.style.height || this.clientHeight, 10),
			left : left_offset,
			top : top_offset
		};
	},
	
	on: function(mouseAction){
		var query = {};
		for(var k in mouseAction){
			if (mouseAction[k]) {
				query[k] = this.attachEvent('on' + k, mouseAction[k]);
			}
		}
		return query;
	},
	
	un: function(mouseAction){
		for(var k in mouseAction){
			this.detachEvent('on' + k, mouseAction[k]);
		}
	},
	
	remove: function () {
		this.parentNode.removeChild(this);
	},
	
	get: function(attr){
		return this.getAttribute(attr);
	},
	
	set: function (name, value) {
		if (value == null || value.length == 0) {
			this.removeAttribute(name, 0) ;
		} else {
			this.setAttribute(name, value, 0);
		}
	},
	
	/*
	to	逐渐改变对象样式
	对opacity渐变前，IE浏览器请先设置对象的filter样式，如：style.filter = 'alpha(opacity=100)'
	@attr	样式目标，格式{样式名1：目标值1, 样式名2: 目标值2 ...}
	@step	完成次数
	*/
	to: function (attr, callback, step) {
		if (typeof attr != 'object') {
			return;
		}
		if (common.isUndefined(step)) {
			step = 10;
		}
		var re = false;
		var m, n, newval, oldval, unit = '';
		for (a in attr) {
			newval = attr[a];		// 目标值
			if (typeof newval != 'number') {
				continue;
			}
			if (a == 'opacity') {
				oldval = is_ie ? this.filters.alpha.opacity : this.style[a] * 100;
			} else {
				oldval = parseInt(this.style[a]);		// 原属性值
			}
			m = Math.ceil(Math.abs(newval - oldval) / step / step);
		//	if (!confirm(this.tagName + '\t' + m + '\t' + newval + '\t' + oldval)) return;
			n = oldval + m * (newval > oldval ? 1 : -1);
			Math.abs(n - newval) <= m ? [n = newval, (delete attr[a])] : re = 1;
			if (a == 'opacity') {
				if (is_ie) {
					this.filters.alpha.opacity = n;
				} else {
					n = n / 100;
				}
			} else {
				unit = 'px';
			} 
		//	window.status = n;
		//	$('r').value = a + '\t\t' + n + unit + '\t\t\n' + $('r').value;
			this.style[a] = n + unit;
		}
		if (re) {
			step--;
			this.to.defer(this, 1, attr, callback, step);
		} else if (callback && callback.func) {
			//setTimeout(callback, 0);
			callback.func.apply(callback.obj ? callback.obj : window);
		}
	},
	
	upZIndex: function () {
		if (this.style.zIndex < common.maxZIndex) {
			this.style.zIndex = ++common.maxZIndex;
		}
	}

};

common.extend(HTMLElement.prototype, common.extendHTMLElement);

common.extend(String.prototype, {
	ulength: function () {
		var c, b = 0, l = this.length;
		while(l) {
			c = this.charCodeAt(--l);
			b += (c < 128) ? 1 : ((c < 2048) ? 2 : ((c < 65536) ? 3 : 4));
		};
		return b;
	},
	usubstring: function (start, end) {
		var s = '', p = 0;
		
		for (i=0;i<this.length;i++) {
			if (start <= p && p < end) {
				s += this.charAt(i);
			}
			c = this.charCodeAt(i);
			p += c < 128 ? 1 : (c < 2048 ? 2 : (c < 65536 ? 3 : 4));
		}
		return s;
	},

	usubstr: function (start, l) {
		var s = '', p = 0;
		for (i=0;i<this.length;i++) {
			if (start <= p && p < start + l) {
				s += this.charAt(i);
			}
			c = this.charCodeAt(i);
			p += c < 128 ? 1 : (c < 2048 ? 2 : (c < 65536 ? 3 : 4));
		}
		return s;
	},

	uindexOf: function (str, starIndex) {
		var p = 0, l = str.length;
		for (i=0;i<this.length;i++) {
			if (this.substring(i, i + l) == str && (starIndex && p >= starIndex)) {
				return p;
			}
			c = this.charCodeAt(i);
			p += c < 128 ? 1 : (c < 2048 ? 2 : (c < 65536 ? 3 : 4));
		}
		return false;
	}
});

common.extend(Function.prototype, {
	/*
	
		function.bind(object, argu1[, agru2...])
		
	*/
	bind: function (object){
		var __method = this;
		var argu = Array.prototype.slice.call(arguments, 1);
		return function (){
			__method.apply(object, argu);
		};
	},
	
	/*
		function.bindEvent(object, argu1[, agru2...])
		程序定义时的参数有两个,分别为event和argu数组，argu[0]等于调用时的argu1，后面类推
	*/

	bindEvent: function (object){
		var __method = this;
		var argu = Array.prototype.slice.call(arguments, 1);
		return function (event){
			event = common.getEvent(event);
			__method.call(object, event, argu);
		};
	},
	
	/*
	*	定时调用程序
	*	function.defer([applyObject, ]time, argu1[, agru2...])
	*/
	
	defer: function() {
		var __method = this, object = null, time = start = 0;
	
		if (typeof arguments[0] == 'object') {
			object = arguments[0];
			time = arguments[1];
			start = 2;
		} else if (typeof arguments[0] == 'number') {
			time = arguments[0];
			start = 1;
		}
	//	alert(typeof arguments[0]);
		
		var argu = Array.prototype.slice.call(arguments, start);
		var fun = function(){
			__method.apply(object, argu);
		}
		return setTimeout(fun, time);
	}
});

var Class = function (){
	var _class = function (){
		this.initialize.apply(this, arguments);
	};
	
	for(i=0; i<arguments.length; i++){
		superClass = arguments[i];
		for(member in superClass.prototype){
			_class.prototype[member] = superClass.prototype[member];
		};
	};
	
	_class.child = function (){
		return new Class(this);
	};
	
	_class.extend = function (f){
		for(property in f){
			_class.prototype[property] = f[property];
		};
	};
	
	return _class;
}

var chgTab = function (box, title, info, act, flash) {
	//this.aaa();
	this.timer = null;
	var t = this;
	
	box = box.split(',');
	var infobox = box[1];
	box = box[0];
//	alert(box);
	
	act = act || 'mouseover';
	common.isUndefined(flash) && (flash = true);

	this.play = function(box, value, title, info) {
		var ts = $(box).find(title);
		for(i = 0; i < ts.length; i++){
			if (i == value) {
				ts[i].active = 1;
				ts[i].className += ' hover';
			} else {
				ts[i].active = null;
				ts[i].className = ts[i].className.replace(' hover', '').replace('hover', '');
			}
		}
		var ts = $(infobox ? infobox : $(box).id + 'Info').find(info);
		var last, curr;
		for(i = 0; i < ts.length; i++){
			if (i == value) {
				curr = ts[i];
			} else if (ts[i].active) {
				last = ts[i];
			} else {
				ts[i].style.display = 'none';
			}
		}
		last = last || ts[0];
		last.active = 0;
		curr.active = 1;
		
		if (flash) {
			last.to({opacity:0}, {func: function() {
					last.style.display = 'none';
					curr.style.display = 'block';
					curr.style.filter = 'alpha(opacity=0)';
					curr.style.opacity = 0;
					curr.to({opacity:100});
				}});
		} else {
			last.style.display = 'none';
			curr.style.display = 'block';
		}
	}

	var ts = $(box).find(title);
	for(i = 0; i < ts.length; i++){
		ts[i].value = i;
		ts[i]['on' + act] = function () {
			if (this.active) {
				return;
			}
			clearTimeout(t.timer);
			t.timer = null;
			t.timer = t.play.defer(100, box, this.value, title, info);
		}
		ts[i].onmouseout = function () {
			clearTimeout(t.timer);
			t.timer = null;
		}
	}
}

function goUrl(u, method) {
	if (!u) return;
	common.isUndefined(method) && (method = 'post');
	var form = $('goUrlForm');
	if (!form) {
		form = $('#body').create('form', {}, {id: 'goUrlForm'});
	}
	form.method = method;
	form.action = u;
	form.submit();
}

window.attachEvent('onload', function () {
	body = document.compatMode == "CSS1Compat" ? document.documentElement : document.body;
});


// 自动更新资源
window.attachEvent('onload', function () {
	if (typeof nextCollect == 'undefined') return;

	nextCollect = Math.max(0, nextCollect);
	var intervalTimer;
	function run () {
		//alert('run');
		var x = new Ajax();
		x.get(CURR_PRE + 'resource/autocollect/' + Math.random(), function(s){
			if (!s) {
				run.defer(5000);
				return;
			}
			if (IS_DEBUG) {
				alert(s);
			}
		});
		
		window.status = '';
		clearInterval(intervalTimer);
	}
	run.defer(nextCollect * 1000);
	intervalTimer = setInterval(function () {window.status = ' ' + (--nextCollect) + ' 秒后进行更新'}, 1000);
});

//缓存背景图片
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

