
//作用：全选
//参数：元素类型,要复选的元素名称
function selectAllCheckBox(objName,selfObjName){
	var coll = document.getElementsByTagName('input')
	if(!coll) return;
	if(coll.length){
		for(var i = 0;i < coll.length;i++){
			if (coll.item(i).name == objName) coll.item(i).checked = document.getElementById(selfObjName).checked;
		}
	}else{
		coll.checked = document.getElementById(selfObjName).checked;
	}
}

//作用：获取列表值
//参数：元素类型
function getValueList(tagName){
	var result = "";
	var coll = document.getElementsByTagName(tagName)
	if(!coll) return result;
	if(coll.length){
		for(var i = 0;i<coll.length;i++){
			if(coll.item(i).checked){
				result += (result == "")?coll.item(i).value:("," + coll.item(i).value);
			}
		}
	}else{
		if(coll.checked){
			result = coll.value;
		}
	}
	return result;
}

//作用：获取资源值，用半角逗号[,]分隔
//参数：对象,值
function getItemValue(tagName,val) {
	if (val == ''){
		document.getElementById(tagName).value = '';
	}
	else {
		if (document.getElementById(tagName).value == ''){
			document.getElementById(tagName).value = val;
		}
		else {
			document.getElementById(tagName).value = document.getElementById(tagName).value +','+ val;
		}
	}
}

//作用：验证按钮是否Disabled
//参数：条件（为空/非空）
function checkDisabled(tagName,objNull) {
	var coll = document.getElementsByTagName('input')
	var temp = false;
	if (objNull == '') temp = true;
	if (!coll) return;
	if (coll.length){
		for(var i = 0;i < coll.length;i++){
			if (coll.item(i).name == tagName)  coll.item(i).disabled = temp;
		}
	}else{
		coll.disabled = temp;
	}
}

//作用：菜单点击后样式切换
//参数：对象
function menuStyle(objName,tag){
	var coll = document.getElementsByTagName('span')
	if(!coll) return;
	if(coll.length){
		for(var i = 0;i < coll.length;i++){
			if (coll.item(i).id == objName){
				if (tag == 'top'){
					coll.item(i).className = 'clickedtop';
				}
				else {
					coll.item(i).className = 'clickedmenu';
				}
			}
			else {
				if (tag == 'top'){
					coll.item(i).className = '';
				}
				else {
					coll.item(i).className = 'menu';
				}
			}
		}
	}
}

//作用：生成随机字符串
//参数：长度,类型
function randomChar(l,t){
	if (t == 1){
		var x = "0123456789poiuytrewqasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM";
	}else{
		var x = "0123456789ABCDEF";
	}
	var tmp = "";
	for(var i = 0;i < l;i ++) {
		tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
	}
	return tmp;
}

//作用：显示/隐藏制定对象
//参数：对象ID
function showTr(id) {
	if (document.getElementById(id).style.display == 'none'){
		document.getElementById(id).style.display = ''
	}else {
		document.getElementById(id).style.display = 'none'
	}
}

//作用：切换前后两张图片
//参数：关闭的图,展开的图,对象id
function changePic(pic1,pic2,id) {
	if (document.getElementById(id).title == '点击展开') {
		document.getElementById(id).src = pic2;
		document.getElementById(id).title = '点击合起';
	}
	else {
		document.getElementById(id).src = pic1;
		document.getElementById(id).title = '点击展开';
	}
}

//作用：弹出窗口
//参数：窗口地址
function openSelWin(url,winWidth,winHeight) {   
	var regWin = window.open(url,'selWin','modal=yes,toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=no,width='+ winWidth +',height='+ winHeight);   
	if (regWin) {   
	  regWin.moveTo((screen.availWidth - winWidth) / 2,(screen.availHeight - winHeight - 12) / 2);   
	  regWin.focus();   
	}   
	return true;   
} 

//作用：获取点击数
//参数：
function getClickNum(virtualRoot,oprateTable,key,PublicID,tagObj,updateTF) {
	xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=click&table='+ oprateTable +'&key='+ key +'&id='+ PublicID +'&updateTF='+ updateTF,0,0,tagObj)
}

//作用：获取回复数
function getReNum(virtualRoot,PublicID,tagObj) {
	xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=getReviewNum&id='+ PublicID,0,0,tagObj)
}

//作用：验证帖子内容
function CheckReviewLength(tag,maxLength) {
	var a = GetLength(tag);
	if (a == 0) {
		alert('1、帖子内容不能为空\n2、请不要使用纯表情或纯图片作为帖子内容'); 
		return false;
	}
	else if (a > maxLength) {
		alert('帖子内容超出字数限制'); 
		return false;
	}
	else {
		return true;
	}
}

//作用：搜索提交
function SearchSubmit(virtualRoot) {
	var key = document.getElementById('keyword').value;
	if (key == ''){
		alert('请输入关键字');
	}
	else {
		location.href = virtualRoot +'/Lib/Search.shtml?page=1&key='+ escape(key);
	}
}

/**********************会员相关操作***********************/
//验证会员阅读权限
function CheckReadGroup(virtualRoot,readscore,infoId,pageNo) {
	var userRead = xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=getUserReadGroup&id='+ infoId +'&readscore='+ readscore,0,2,'');
	if (userRead == 'True'){
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=checkReadGroup&id='+ infoId +'&pageNo='+ pageNo,0,0,'Info_'+ infoId);
	}
}

//验证用户是否登录
function GetUserLoginForm(virtualRoot,action,tempId,formId) {
	if (UserOnline(virtualRoot,formId)){
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=onlineTime',0,0,'');
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=showUserInfo',0,0,'LoginForm_'+ formId);
	}
	else {
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action='+ action +'&tempid='+ tempId +'&id='+ formId,0,0,'LoginForm_'+ formId);
	}
}

//定时统计用户信息
function UserOnline(virtualRoot,formId) {
	var userLogin = xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=checkUser',0,2,'');
	if (userLogin == 'True'){
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=onlineTime',0,0,'');
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=showUserInfo',0,0,'LoginForm_'+ formId);
		return true;
	}
	else {
		return false;
	}
}

//用户退出
function userLogout(virtualRoot) {
	if (confirm('是否真的要退出？')){
		xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=userLogout',0,0,'');
		location.reload();
	}
}

//验证登录
function ChkUserLogin(virtualRoot,action,formId) {
	var errCode = '';
	var saveCookie = '';
	var cookieSave = '';
	var tempid = document.getElementById('tempId').value;
	var usn = document.getElementById('usn').value;
	var psw = document.getElementById('psw').value;
	var code = document.getElementById('code').value;
	var saveCookie = document.getElementById('savecookie').checked;
	if (saveCookie) cookieSave = 1;
	if (usn == ''){
		errCode = errCode +'用户名不能为空\n';
	}
	if (psw == ''){
		errCode = errCode +'密码不能为空\n';
	}
	if (code == ''){
		errCode = errCode +'验证码不能为空';
	}
	if (errCode != ''){
		alert('错误提示：\n\n'+ errCode);
	}
	else {
		var a = xmlHttpPost(virtualRoot +'/Lib/XmlHttp.asp','action=checkUserLogin&tempid='+ tempid +'&usn='+ usn +'&psw='+ psw +'&code='+ code +'&savecookie='+ cookieSave +'&id='+ formId,0,2,'LoginForm_'+ formId);
		if (a == '0'){
			location.reload();
		}
		else {
			document.getElementById('LoginForm_'+ formId).innerHTML = a;
		}
	}
}

//作用：显示评论
function getReview(virtualRoot,reviewType,PublicID,pageNo,tempId,showType) {
	if (showType == 'List') {
		xmlHttpPost(virtualRoot +'/Lib/xmlHttp.asp','action=getReviewList&id='+ PublicID +'&reviewType='+ reviewType +'&pageNo='+ pageNo +'&tempid='+ tempId,0,0,'P_'+ PublicID);
	}
}

/**********************会员相关操作***********************/


/**********************翻页操作***********************/

//作用：信息块分页跳转
//参数：总页数,目标页码,位置,目标对象前缀,附加传递参数
function changePage(virtualRoot,action,pCount,pButton,pPlace,pType,tagObj,condition) {
	var pNo = '';
	if (pButton == 'First'){
		pNo = 1;
	}
	else if (pButton == 'Previous'){
		if (document.getElementById('P_'+ tagObj +'_No0')) pNo = Number(document.getElementById('P_'+ tagObj +'_No0').innerHTML) - 1;
		if (document.getElementById('P_'+ tagObj +'_No1')) pNo = Number(document.getElementById('P_'+ tagObj +'_No1').innerHTML) - 1;
		if (pNo < 1) pNo = 1
	}
	else if (pButton == 'Next'){
		if (document.getElementById('P_'+ tagObj +'_No0')) pNo = Number(document.getElementById('P_'+ tagObj +'_No0').innerHTML) + 1;
		if (document.getElementById('P_'+ tagObj +'_No1')) pNo = Number(document.getElementById('P_'+ tagObj +'_No1').innerHTML) + 1;
		if (pNo > pCount) pNo = pCount
	}
	else if (pButton == 'Last'){
		pNo = pCount;
	}
	else {
		pNo = Number(pButton);
	}
	if (pType == 0){
		for (var i = 1;i <= pCount;i ++ ){
			if (i == pNo) document.getElementById('P_'+ tagObj +'_'+ i).style.display = '';
			else document.getElementById('P_'+ tagObj +'_'+ i).style.display = 'none';
		}
	}
	else {
		xmlHttpPost(virtualRoot +'/Lib/xmlHttp.asp','action='+ action +'&id='+ tagObj +'&page='+ pNo +'&condition='+ condition,0,0,'P_'+ tagObj)
	}
	if (document.getElementById('P_'+ tagObj +'_No0')) document.getElementById('P_'+ tagObj +'_No0').innerHTML = pNo;
	if (document.getElementById('P_'+ tagObj +'_No1')) document.getElementById('P_'+ tagObj +'_No1').innerHTML = pNo;
}
/**********************翻页操作***********************/

//作用：xmlHttp应用
//参数：要接收的URL,传递的值,传递类型（0.POST/1.GET）,处理方式(0.输出到对象/1.传递给对象值/2.返回值),返回的ID
function xmlHttpPost(url,valueStr,postType,oprateType,id)
{
	if (oprateType == 0) {
		if (document.getElementById(id)) document.getElementById(id).innerHTML = val;
	}
	xmlhttp = false;
	var postStr = 'POST';
	if (postType == 1) {
		postStr = 'GET'
	}
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
		if (xmlhttp.overrideMimeType) {
			xmlhttp.overrideMimeType('text/xml');
		}
	}else if (window.ActiveXObject) {
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){
			}
		}
	}
	if (!xmlhttp) {
		alert('Can not init XMLHttpRequest!');
		return false;
	}
	xmlhttp.open(postStr,url,false);
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xmlhttp.send(valueStr);
	var val = '';
	if (xmlhttp.readyState == 4){
		if (xmlhttp.status == 200){
			val = unescape(xmlhttp.responseText);
		}
		else {
			val = 'Please wait...';
		}
	}
	else if (xmlhttp.readyState == 1){
		val = 'Now Loading...';
	}
	else if (xmlhttp.readyState == 2){
		val = 'Load Completed...';
	}
	else if (xmlhttp.readyState == 3){
		val = 'Load interactiving...';
	}
	else {
		val = 'Now Loading...';
	}
	if (oprateType == 0) {
		if (document.getElementById(id)) document.getElementById(id).innerHTML = val;
	}
	else if (oprateType == 1) {
		if (document.getElementById(id)) document.getElementById(id).value = val;
	}
	else if (oprateType == 2) {
		return val;
	}
	else if (oprateType == 3) {
		alert(val);
	}
	else if (oprateType == 4) {
		document.body.innerHTML = val;
	}
	else if (oprateType == 5) {
		document.write(val);
	}
}

//作用：在焦点处插入内容
//参数：对象
function setCaret(textObj){   
	if (textObj.createTextRange){   
		textObj.caretPos = document.selection.createRange().duplicate();   
	}   
}

//参数：对象,要插入的值
function insertAtCaret (textObj,textFeildValue) { 
	if(document.all) {   
		if (textObj.createTextRange && textObj.caretPos) { 
			var caretPos = textObj.caretPos; 
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ''?textFeildValue + '' : textFeildValue; 
		}else{ 
			textObj.value = textFeildValue; 
		} 
	}else{ 
		if(textObj.setSelectionRange){ 
			var rangeStart = textObj.selectionStart; 
			var rangeEnd = textObj.selectionEnd; 
			var tempStr1 = textObj.value.substring(0,rangeStart); 
			var tempStr2 = textObj.value.substring(rangeEnd); 
			textObj.value = tempStr1 + textFeildValue + tempStr2; 
		}else{ 
			alert("This version of Mozilla based browser does not support setSelectionRange"); 
		} 
	} 
}   

/*************************************************
	Validator v1.05表单验证类开始
	code by 我佛山人
	wfsr@msn.com
*************************************************/
 Validator = {
	Require : /.+/,
	Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/,
	Mobile : /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/,
	Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
	IdCard : "this.IsIdCard(value)",
	Currency : /^\d+(\.\d+)?$/,
	Number : /^\d+$/,
	Zip : /^[1-9]\d{5}$/,
	QQ : /^[1-9]\d{4,8}$/,
	Integer : /^[-\+]?\d+$/,
	Double : /^[-\+]?\d+(\.\d+)?$/,
	English : /^[A-Za-z]+$/,
	Chinese :  /^[\u0391-\uFFE5]+$/,
	Username : /^[a-z]\w{3,}$/i,
	UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
	IsSafe : function(str){return !this.UnSafe.test(str);},
	SafeString : "this.IsSafe(value)",
	Filter : "this.DoFilter(value, getAttribute('accept'))",
	Limit : "this.limit(value.length,getAttribute('min'),  getAttribute('max'))",
	LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
	Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
	Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
	Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",
	Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
	Custom : "this.Exec(value, getAttribute('regexp'))",
	Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
	ErrorItem : [document.forms[0]],
	ErrorMessage : ["错误提示：\n"],
	Validate : function(theForm, mode){
		var obj = theForm || event.srcElement;
		var count = obj.elements.length;
		this.ErrorMessage.length = 1;
		this.ErrorItem.length = 1;
		this.ErrorItem[0] = obj;
		for(var i=0;i<count;i++){
			with(obj.elements[i]){
				var _dataType = getAttribute("dataType");
				if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined")  continue;
				this.ClearState(obj.elements[i]);
				if(getAttribute("require") == "false" && value == "") continue;
				switch(_dataType){
					case "IdCard" :
					case "Date" :
					case "Repeat" :
					case "Range" :
					case "Compare" :
					case "Custom" :
					case "Group" : 
					case "Limit" :
					case "LimitB" :
					case "SafeString" :
					case "Filter" :
						if(!eval(this[_dataType]))	{
							this.AddError(i, getAttribute("msg"));
						}
						break;
					default :
						if(!this[_dataType].test(value)){
							this.AddError(i, getAttribute("msg"));
						}
						break;
				}
			}
		}
		if(this.ErrorMessage.length > 1){
			mode = mode || 1;
			var errCount = this.ErrorItem.length;
			switch(mode){
			case 2 :
				for(var i=1;i<errCount;i++)
					this.ErrorItem[i].style.color = "red";
			case 1 :
				alert(this.ErrorMessage.join("\n"));
				this.ErrorItem[1].focus();
				break;
			case 3 :
				for(var i=1;i<errCount;i++){
				try{
					var span = document.createElement("SPAN");
					span.id = "__ErrorMessagePanel";
					span.style.color = "red";
					this.ErrorItem[i].parentNode.appendChild(span);
					span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"* ");
					}
					catch(e){alert(e.description);}
				}
				this.ErrorItem[1].focus();
				break;
			default :
				alert(this.ErrorMessage.join("\n"));
				break;
			}
			return false;
		}
		return true;
	},
	limit : function(len,min, max){
		min = min || 0;
		max = max || Number.MAX_VALUE;
		return min <= len && len <= max;
	},
	LenB : function(str){
		return str.replace(/[^\x00-\xff]/g,"**").length;
	},
	ClearState : function(elem){
		with(elem){
			if(style.color == "red")
				style.color = "";
			var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
			if(lastNode.id == "__ErrorMessagePanel")
				parentNode.removeChild(lastNode);
		}
	},
	AddError : function(index, str){
		this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
		this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
	},
	Exec : function(op, reg){
		return new RegExp(reg,"g").test(op);
	},
	compare : function(op1,operator,op2){
		switch (operator) {
			case "NotEqual":
				return (op1 != op2);
			case "GreaterThan":
				return (op1 > op2);
			case "GreaterThanEqual":
				return (op1 >= op2);
			case "LessThan":
				return (op1 < op2);
			case "LessThanEqual":
				return (op1 <= op2);
			default:
				return (op1 == op2);            
		}
	},
	MustChecked : function(name, min, max){
		var groups = document.getElementsByName(name);
		var hasChecked = 0;
		min = min || 1;
		max = max || groups.length;
		for(var i=groups.length-1;i>=0;i--)
			if(groups[i].checked) hasChecked++;
		return min <= hasChecked && hasChecked <= max;
	},
	DoFilter : function(input, filter){
return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g, filter.split(/\s*,\s*/).join("|")), "gi").test(input);
	},
	IsIdCard : function(number){
		var date, Ai;
		var verify = "10x98765432";
		var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
		var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
		if(re == null) return false;
		if(re[1] >= area.length || area[re[1]] == "") return false;
		if(re[2].length == 12){
			Ai = number.substr(0, 17);
			date = [re[9], re[10], re[11]].join("-");
		}
		else{
			Ai = number.substr(0, 6) + "19" + number.substr(6);
			date = ["19" + re[4], re[5], re[6]].join("-");
		}
		if(!this.IsDate(date, "ymd")) return false;
		var sum = 0;
		for(var i = 0;i<=16;i++){
			sum += Ai.charAt(i) * Wi[i];
		}
		Ai +=  verify.charAt(sum%11);
		return (number.length ==15 || number.length == 18 && number == Ai);
	},
	IsDate : function(op, formatString){
		formatString = formatString || "ymd";
		var m, year, month, day;
		switch(formatString){
			case "ymd" :
				m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
				if(m == null ) return false;
				day = m[6];
				month = m[5]*1;
				year =  (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
				break;
			case "dmy" :
				m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
				if(m == null ) return false;
				day = m[1];
				month = m[3]*1;
				year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
				break;
			default :
				break;
		}
		if(!parseInt(month)) return false;
		month = month==0 ?12:month;
		var date = new Date(year, month-1, day);
        return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
		function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
	}
 }
/*************************************************
	Validator v1.05表单验证类结束
	code by 我佛山人
	wfsr@msn.com
*************************************************/

function GetLength(obj)
{
	var oEditor = FCKeditorAPI.GetInstance(obj) ;
	var oDOM = oEditor.EditorDocument ;
	var iLength ;
	if ( document.all )		// If Internet Explorer.
	{
		iLength = oDOM.body.innerText.length ;
	}
	else					// If Gecko.
	{
		var r = oDOM.createRange() ;
		r.selectNodeContents( oDOM.body ) ;
		iLength = r.toString().length ;
	}
//	alert(iLength + 'byte' ) ;
	return iLength;
}

function InsertHTML(obj,str)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(obj) ;

	// Check the active editing mode.
	if ( oEditor.EditMode == FCK_EDITMODE_WYSIWYG )
	{
		// Insert the desired HTML.
		oEditor.InsertHtml(str) ;
	}
	else
		alert( 'You must be on WYSIWYG mode!' ) ;
}

function SetContents(obj,str)
{
	// Get the editor instance that we want to interact with.
	var oEditor = FCKeditorAPI.GetInstance(obj) ;

	// Set the editor contents (replace the actual one).
	oEditor.SetHTML(str) ;
}
