//history
(function(){
	window.History=[];
	History.firstLoad=true;
	function setHash(hash){
		if(document.all&&History.cacheIframe){
			var local=History.cacheWindow.location;
			if(local.hash.slice(1)!=hash){
				setTimeout(function(){
					History.cacheIframe.contentWindow.location=local.protocol+"//"+location.host+local.pathname+"?r="+Math.random()+"#"+hash;
				},50);
			}
		}
	}
	function onLocationChange(){
		var hash=location.hash.slice(1),listener=History.listener;
		if(History.firstLoad||hash!=History.curLocation||History.locationChanged){
			try{
				listener.method.apply(null,listener.param.concat([hash]));
				History.locationChanged=false;
				History.curLocation=hash;
				if(!History.iframeLocationChange&&!History.firstLoad){
					setHash(hash);
				}
				History.firstLoad=false;
				History.iframeLocationChange=false;
			}catch(e){alert("Exception:"+e.description||e.message);}
		}
	}
	if(document.all){
		document.write('<iframe name="__historyCache__" id="__historyCache__" src="../common/blank.html?0#'+location.hash.slice(1)+'" style="border:0;width:1px;height:1px;left:0;top:0;position:absolute;visibility:hidden"></iframe>');
		History.cacheIframe=document.getElementById("__historyCache__");
	}
	History.addListener=function(method,param){
		this.listener={"method":method,"param":param?(param.constructor==Array?param:[param]):[]};
		this.cacheWindow=document.__historyCache__;
		onLocationChange();
		window.setInterval(onLocationChange,100);
	}
	History.add=function(hash){
		if(hash==this.curLocation)return;
		this.push(hash);
		location.hash=hash;
	}
	History.getIframeLocation=function(hash){
		this.iframeLocationChange=true;
		this.add(hash);
	}
})();
function splitHash(hash){
	var a=hash.split("/"),h={};
	for(var i=0,length=a.length;i<length;i++){
		var b=a[i].split(":");
		h[b[0]]=b[1];
	}
	return h;
}
function checkAddHash(key,value){
	var hash=location.hash.slice(1),re=new RegExp("(^|\/)"+key+":(.*?)(\/|$)","i"),m=re.exec(hash);
	if(m){
		if(m[2]!=key)return hash.replace(re,"$1"+key+":"+value+"$3");
	}else{return hash+"/"+key+":"+value}
}

//初始化3态按钮
function changeBtnMode(btn){
		var height=btn.offsetHeight||parseInt(btn.getStyle("height"));
		btn.hideFocus="true";
		btn.listen("onmouseover",function(){btn.style.backgroundPosition="0 -"+height+"px";});
		btn.listen("onmousedown",function(){btn.style.backgroundPosition="0 -"+(2*height)+"px";});
		btn.listen("onmouseup",function(){btn.style.backgroundPosition="0 -"+height+"px";});
		btn.listen("onmouseout",function(){btn.style.backgroundPosition="0 0";});
		btn.style.backgroundPosition="0 0";
		btn.removeAttribute("mode");
}
function replaceBtn(object){
	try{
		$("*[@mode='img']",$.$(object)||document.body).each(function(){
			changeBtnMode(this);
		});
	}catch(e){}
}
//请求xsl和xml，转化为html，添加到obj内
function transToHTML(obj,options){
	obj=$.appfn(obj);
    if (!obj) return;

	var xsl,xml;
	var pXslToHtml=function(xsl,xml){
		try{
			if($.browser.msie){
				return xml.transformNode(xsl);
			}else{
				var xsltProcessor=new XSLTProcessor();
				xsltProcessor.importStylesheet(xsl);
				var result=xsltProcessor.transformToDocument(xml);
				var xmls = new XMLSerializer();
				return xmls.serializeToString(result);
			}
		}catch(e){showAlert("系统错误",e.description||e.message,null,4)}
	}
	var toHtml=function(obj,xsl,xml,options){
		obj.innerHTML=pXslToHtml(xsl,xml).replace(/&gt;/gi,">").replace(/&lt;/gi,"<").replace(/&amp;/g,"&");
		replaceBtn(obj);
		if(options.onComplete){
			options.onComplete.apply(null,[xml]);
		}
	}
	var loadXml=function(){
		if(typeof options.xml=="object"){
			toHtml(obj,xsl,options.xml,options);
		}else{
			obj.sendAjax(options.xml,{
				onSuccess:function(){
					xml=this.responseXML;
					toHtml(obj,xsl,xml,options);
				}
			});
		}
	}
	var saveObj=$.$(options.saveXslObj);
	if(saveObj&&saveObj.xsl){
		xsl=saveObj.xsl;
		loadXml();
	}else{
		obj.sendAjax(options.xsl,{
			onSuccess:function(){
				xsl=this.responseXML;
				if(saveObj)saveObj.xsl=xsl;
				loadXml();
			}
		});
	}
}

//分页算法
function splitPage(no,all){
	var pages=[],s="",n1=no-3,n2=no+3;
	if(no<9){
		n1=1;
		n2=no<5?7:n2;
		if(n2>all)n2=all;
	}else if((all-no)<8){
		n1=(all-no)<4?all-6:n1;
		n2=all;
	}
	if(n1>1)pages.push(".");
	for(var i=n1;i<=n2;i++){
		pages.push(i);
	}
	if(n2<all)pages.push(".");
	return pages;
}
//分页
function showCurPage(sObj,xsl,xml,onComplete,pageParam,pageNo,box){
	transToHTML(box||"contentDiv",{
		"saveXslObj":sObj,
		"xml":xml.replace(new RegExp("\\b"+pageParam+"=(\\d*)","g"),pageParam+"="+pageNo),
		"xsl":xsl,
		"onComplete":onComplete
	});
}

function createPages(xml,fn,pid){
	var pages=$.appfn((pid||"pages")),pn=$.nodes(xml.documentElement,"pages/pageno"),pall=$.nodes(xml.documentElement,"pages/pagecount");
	if(pages&&pn.length>0&&pall.length>0){
		var no=$.text(pn[0],"text()")*1,total=$.text(pall[0],"text()")*1,str=[],num;
		if(total<=0)return;
		var p=splitPage(no,total);
                  
    str.push('<div class="fenye">');
		str.push('<div class="fenye_content">'); 
		str.push('<span class="span_1" style="width:auto;padding:0px 10px 0px 10px;">当前 '+no+' / '+total+'</span>');
		str.push('<ul id="fenye" style="padding:0px;list-style:none;float:left;padding:0;margin:0;">');
		
		
		str.push(no==1?'':'<li style="width:auto;float:left;padding:0px;"><a href="javascript:void(0)" page="'+(no-1)+'">上一页</a></li>');
		for(var i=0;i<p.length;i++){
			if(p[i]==".")
				str.push('<li style="float:left;width:auto;padding:0px;">...</li>');
			else
				str.push(no==p[i]*1?'<li style="float:left;width:auto;padding:0px;"><a href="javascript:void(0)">'+p[i]+'</a></li>':'<li style="float:left;width:auto;padding:0px;"><a href="javascript:void(0)" page="'+p[i]+'">'+p[i]+'</a></li>');
		}
		str.push(no==total?'':'<li style="width:auto;padding:0px;float:left;"><a href="javascript:void(0)" page="'+(no+1)+'" >下一页</a></li>');
		
		str.push('<li class="clear"></li>');
		str.push('</ul></div></div>');
		
		pages.innerHTML=str.join("");
		$("a",pages).each(function(){
			this.onclick=function(){
				fn(this.getAttribute("page"));
			}
		});
		pages.curPage=no;
	}
}

//请求单个页面，box为容器
function requestPage(box,url){
	var con=$.appfn(box);
	con.sendAjax(url,{
		onLoadInit:function(){
			/*con.innerHTML="数据正在加载中，请稍候......"*/
		},
		onSuccess:function(){
			var query=splitQuery(url),txt=this.responseText.replace(new RegExp("\\{\\@([\\w\\.]+)\\}","g"),function($0,$1){
					try{return eval($1)}catch(e){return $1}
				});
			con.query=query.pop();
			for(var i=0,length=query.length;i<length;i++){
				if(query[i][0]!=null&&query[i][1]!=null){
					txt=txt.replace(new RegExp("(\\{\\#("+query[i][0]+")\\})","g"),query[i][1]==null?"$1":query[i][1]);
				}
			}
			var scripts=txt.match(/<script((.|\n|\r)*?)<\/script>/gi)||[];
			con.innerHTML=txt.replace(/<script((.|\n|\r)*?)<\/script>/gi,"");
			replaceBtn(con);
			for(var i=0;i<scripts.length;i++){
				var script=scripts[i].replace(/<script.*?>((.|\n|\r)*)<\/script>/i,"$1");
				try{
					eval(script);
				}catch(e){}
			}
		}
	});
}
//得到指定ID表单元素的值
var getChoose=function(type, element){
    var value=type=="radio"?null:[],el=type=="select-multiple"?element.options:(element.form)[element.name];
    if(typeof el.length=="undefined")el=[el];
    for(var i=0;i<el.length;i++){
        if(el[i][type=="select-multiple"?"selected":"checked"])
            type=="radio"?(value=el[i].value):value.push(el[i].value);
    }
    return value;
}

window.$v=function(element){
	var element=$.$(element)
    var type=element.type;
	if("text,hidden,password,file,textarea,select-one,button".inStr(type)) {
		return element.value;
	} else if("radio,checkbox,select-multiple".inStr(type)) {
		return getChoose(type, element);
    }
	return undefined;
}
//将某表单的元素值生成hash格式
window.$F=function(form){
	var el=form.elements,values={},name;
	for(var i=0;i<el.length;i++){
		name=el[i].name;
		if(typeof values[name]=="undefined") {
			values[name]=$v(el[i]);
        }
	}
	return values;
}
//得到浏览器里参数的值。如：?op=edit
function getParam(name){
	var s=location.search,a=s.slice(1).split("&"),value=null;
	for(var i=0;i<a.length;i++){
		var ta=a[i].split("=");
		if(ta[0].trim()==name){
			value=ta[1].trim();
			break;
		}
	}
	return value;
}
function splitQuery(str){
	var begin=str.indexOf("?"),query=begin==-1?"":str.slice(begin+1),params=query.split("&"),obj=[],o={};
	for(var i in o){o[i]=null;delete o[i]}
	for(var i=0,length=params.length;i<length;i++){
		var param=params[i].split("=");
		obj.push(param);
		o[param[0]]=param[1];
	}
	obj.push(o);
	return obj;
}
//iframe的onload
function iframeOnLoad(ow,onComplete){
	var oDoc=ow.contentWindow.document,str;
	if($.browser.msie){
		var str=oDoc.body.innerText.slice(1).replace(/\n[\s]*\-/g,"\n");
		if(str=="")
			return;
		xml=$.toXml(str).ownerDocument;
	}
	else{
		if((oDoc+"").indexOf("XML")==-1)
			return;
		xml=oDoc;
	}
	if(onComplete&&onComplete.constructor==Function)
		onComplete(xml);
}
//解析返回值成json对象
function parseReturnMsg(xml){
	try{
		var doc=xml.documentElement;
		var err=$.nodes(doc,"error"),succ=$.nodes(doc,"succeed"),flag=err.length>0?0:(succ.length>0?1:2),msg=flag==0?err:(flag==1?succ:[]);
		var s=[];
		for(var i=0;i<msg.length;i++){
			s.push($.text(msg[i],"text()"));
		}
		return {"status":flag==0?"error":(flag==1?"ok":"unsure"),"msg":s,"description":s.join("<br />")}
	}catch(e){
		return {"status":"error","msg":[],"description":"出现异常！"+(e.description||e.message)}
	}
}
//取某个元素的innerHTML
function getHtml(obj){
	if(!$.browser.msie){
		var elements=document.getElementsByTagName("input",obj);
		for(var i=0;i<elements.length;i++){
			switch(elements[i].type){
				case "radio":
				case "checkbox":
					if(elements[i].checked)
						elements[i].setAttribute("checked",elements[i].checked);
					else
						elements[i].removeAttribute("checked");
					break;
				case "text":
				case "hidden":
				case "password":
				case "file":
				case "button":
					elements[i].setAttribute("value",elements[i].value);break;
			}
		}
		elements=document.getElementsByTagName("select",obj);
		for(var i=0;i<elements.length;i++){
			var options=elements[i].options;
			for(var j=0;j<options.length;j++){
				if(options[j].selected)
					options[j].setAttribute("selected",options[j].selected);
				else
					options[j].removeAttribute("selected");
			}
		}
		elements=document.getElementsByTagName("textarea",obj);
		for(var i=0;i<elements.length;i++)
			elements[i].innerHTML=elements[i].value;
	}
	return obj.innerHTML;
}
//拷贝到剪贴板
function copyText(text){
	if(window.clipboardData){
		window.clipboardData.setData("Text",text);
		msg('己经成功复制到您的剪贴板中！');
	}else if(window.netscape){
		try{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		    msg('己经成功复制到您的剪贴板中！');
		}catch(e){
            msg("浏览器不支持复制功能，请手动复制");
			//showAlert("警告",'您的firefox安全限制限制您进行剪贴板操作，请打开 "about:config" 将signed.applets.codebase_principal_support "设置为true" 之后重试',null,1);
			return false;
		}
		var clip,trans,str={},clipid;
		if(!(clip=Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard))) return;
		if(!(trans=Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable))) return;
		trans.addDataFlavor("text/unicode");
		str=Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		str.data=text;
		trans.setTransferData("text/unicode",str,text.length*2);
		clipid=Components.interfaces.nsIClipboard;
		try{
			clip.setData(trans,null,clipid.kGlobalClipboard);
		}catch(e){return false}
	}
}
//添加到书签
function addBookmark(title,url){
	if (document.all){ 
		window.external.AddFavorite(url,title);
	} 
	else if (window.sidebar) 
	{ 
		window.sidebar.addPanel(title,url,"");
	} 
}

/*上传图片*/
function uploadPhoto(){
	var val=$.$("UpFile").value,fileext=val.slice(val.lastIndexOf(".")).toLowerCase();
	if(!".jpg,.gif,.jpeg,.png,.bmp".inStr(fileext)){
		if($.$("msg_server")){
			$.$("msg_server").innerHTML="对不起，系统仅支持标准格式的照片，请您调整格式后重新上传!";
			$.$("msg_server").style.display="block";
		}		
	}else{
		if($.browser.firefox){
			$.$("preview").innerHTML="您已经选择文件:<br />"+val.slice(val.lastIndexOf("\\")+1);
		}else{
			$.$('preview').innerHTML='<img src="'+val+'" width="100px" alt="" />';
		}
	}
}
/*全选/全不选*/
function checkAll(box){
	$('input[@type="checkbox" class="borderNone"]',$.$(box?box:'contentDiv')).each(function(){
		this.checked=true;
	})
}
function checkNotAll(box){
	$('input[@type="checkbox" class="borderNone"]',$.$(box?box:'contentDiv')).each(function(){
		this.checked=false;
	});
}


//取回密码
function getPasswd(){
	function show_getpwd_form(email)
	{
		var w=new _$w()
		var send_msg=function(){
			var email = w.form.email.value.trim();
			if(email==""){
				msg('请填写您的注册邮箱地址！');
			}else{
				var pras="op=getPasswd&email="+email;
				({}).sendAjax("../space/login.php?"+pras,{
					onSuccess:function(){
					var result_msg=parseReturnMsg(this.responseXML);
					if(result_msg.status=='ok'){
							msg('重置密码邮件己发送到您的邮箱,请查收！', 'location.reload()','提示');
						}
						else
						{
							msg(result_msg.description, 'location.reload()','提示');
						}
					},
					onFailure:function(){msg('系统繁忙,请重试！')}
				});
			}
		}
		
		var contentstr = '<ul class="img_list4"><li class="time_color">输入您的注册邮箱</li><li><input type="text" name="email" class="input_bg"/></li>'
		w.content(contentstr);
		w.title("取回密码")
		w.width(301)
		w.add_bt({"value":"确定","type":"button","echo":send_msg})
		w.add_bt({"value":"取消","type":"button"})
		w.show()	
		w.height()
	}
	show_getpwd_form();
}

//加为好友、删除好友（整站）
function gFriendOp(uid,uhash,uname,logo,op, obj){
    if (!IfLogin()) {
        msg("尚未登录，请先登录！")
        return false;
    }

	function show_friend(uid,uhash,uname,logo,op)
	{
		var msg_title='';
		if(op == 'add'){
			msg_title = '添加好友';
			contentstr='<div class="dzh"><div class="floatLeft"><img src="'+logo+'" /></div><p><br />您确定要加'+uname+'为好友吗?</p><ul><li><p>同时您也会出现在'+uname+'的好友列表。<br /></p><br /><br /><br /><br /></li></ul></div>';
		}else{
			msg_title = '删除好友';
			contentstr='<div class="dzh"><div class="floatLeft"><img src="'+logo+'" /></div><p><br />您确定要和'+uname+'解除好友关系吗?</p><ul><li><p>同时您将从'+uname+'的好友列表中删除。<br /><br /><br /><br /></p><br /></li></ul></div>';
		}
		var w=new _$w()
		var send_msg=function(){
			//alert(w.form.content.value)
			var pras="op="+op+"&uid="+uid+"&uhash="+uhash;
			({}).sendAjax("../space/friend.php?"+pras,{
				onSuccess:function(){
				var result_msg=parseReturnMsg(this.responseXML);
				if(result_msg.status=='ok'){
						alertMsg(msg_title+uname+'成功！', '','提示');
                        if (obj) {
                            obj.parentNode.innerHTML = 'TA已是你好友'
                        }
					}
					else
					{
						alertMsg(result_msg.description, '','提示');
					}
				},
				onFailure:function(){msg('操作失败！')}
			});
		}
		
		//contentstr='<p>分类名称：<input name="kindName" type="text" value="'+name+'"/></p>';
		w.content(contentstr);
		w.title(msg_title)
		w.width(450)
		w.add_bt({"value":"确定","type":"button","echo":send_msg})
		w.add_bt({"value":"取消","type":"button"})
		w.show()	
		w.height()
	}
	show_friend(uid,uhash,uname,logo,op);
}


//创建模板
function gSaveSkin(keys){
	function show_skin(keys)
	{
		msg_title = '创建模板第二步';
		contentstr='<div class="bcmb"><div class="time_color">请认真写这个模板的主题信息</div><p>模板名称</p><input name="skin_name" type="text" class="input_bg" /><p>模板分类</p><select name="category" class="input_bg"><option value="1">明星</option><optionvalue="2">卡通</option><option value="3">爱情</option><option value="4">风景</option><option value="5">游戏</option><option value="6">影视</option><option value="7">运动</option><option value="8">职业</option><option value="9">另类</option><option value="10">其他</option></select></div>';
		var w=new _$w()
		var send_msg=function(){
			//var pras="op="+op+"&uid="+uid;
			skin_name=w.form.skin_name.value;
			category=w.form.category.value;
			keys+="skin_name="+skin_name+"&";
			keys+="category="+category;

			if(skin_name == '')
			{
				msg('请输入模板名称！');
				return false;
			}
			if(skin_name.length > 30)
			{
				msg('模板名称最多为10个汉字！');
				return false;
			}
			if(category == 0)
			{
				msg('请选择模板分类！');
				return false;
			}
			
			var css_save_ok=function(xml,text){
				var key=xv(xml,"/root/result")
				if(key!=1){
					var msg_ok=new _$w()
					msg_ok.content("<div style='padding:20px 30px'>模板创建成功，<br/>并己设置为您的默认模板！</div>")
					msg_ok.add_bt({"value":"确定","type":"button","echo":"location.href='../space/skins.php?op=myskin'"})
					msg_ok.width(260)
					msg_ok.show()
					//msg("模板保存成功，并己设置为您的默认模板！")
				}else
					msg(key)
			}
			SetAjax("../space/skins.php?op=saveSkin&from=0","post:"+keys,css_save_ok)
		}
		
		w.content(contentstr);
		w.title(msg_title)
		w.width(300)
		w.add_bt({"value":"确定","type":"button","echo":send_msg})
		w.show()	
		w.height()
	}
	if(skin_from == "1")
	{
		var css_save_ok=function(xml,text){
			var key=xv(xml,"/root/result")
			if(key!=1){
				var msg_ok=new _$w()
				msg_ok.content("<div style='padding:20px 30px'>模板编辑成功，<br/>如未更新请按F5刷新！</div>")
				msg_ok.add_bt({"value":"确定","type":"button","echo":"location.href='../space/skins.php?op=myskin'"})
				msg_ok.width(260)
				msg_ok.show()
			}else
				msg(key)
		}
		SetAjax("../space/skins.php?op=saveSkin&skin_from=1&skin_id="+skin_id,"post:"+keys,css_save_ok)
	}else{
		show_skin(keys);
	}
}

//发送消息（整站）
function gSendMsg(uid,uname, title, body){
    if (!IfLogin()) {
        msg("尚未登录，请先登录！")
        return false;
    }

	function show()
	{
		var w=new _$w()
		var send_msg=function(){
			//alert(w.form.content.value)
			var uname 	= w.form.uname.value.trim();
			var title 	= w.form.title.value.trim();
			var content = w.form.content.value.trim();
		
			if(uname==""){
				msg('请填写消息接收者的帐号！', w.form.uname.focus(),'提示');
			}else if(title==""){
				msg('请填写消息主题！', w.form.title.focus(),'提示');
			}else if(content==""){
				msg('请填写消息内容！', w.form.content.focus(),'提示');
			}else{	
				var pras="op=save&reciver="+uid+"&title="+title+"&content="+content+"&_r="+Math.random();
				({}).sendAjax("../space/message.php?"+pras,{
					onSuccess:function(){
					var result_msg=parseReturnMsg(this.responseXML);
					if(result_msg.status=='ok'){
							msg('消息发送成功！');
						}
						else
						{
							msg(result_msg.description);
						}
					},
					onFailure:function(){msg('消息发送失败！')}
				});
			}
		}
		contentstr='<ul class="img_list13"><li><p>发 给：'+uname+'</p></li><li><p>主 题：'
        +(title?title+'<input type="hidden" name="title" value="'+title+'" />':'<input type="text" id="title" class="input_bg name="title" />')
        +'</p></li><li class="marginTop5"><p>内 容：<textarea name="content" class="input_bg">'+(body?body:'')+'</textarea><input name="uname" type="hidden" value="'+uname+'"/></p></li></ul>';
		w.content(contentstr);
		w.title("发送消息")
		w.width(415)
		w.add_bt({"value":"发送","type":"button","echo":send_msg})
		w.add_bt({"value":"取消","type":"button"})
		w.show()	
		w.height()
	}
	show();
}
//打招呼（整站）
function gPoke(uid,uname,logo){
    if (!IfLogin()) {
        msg("尚未登录，请先登录！")
        return false;
    }
	function show(uid,uname,logo)
	{
		var w=new _$w()
		var send_msg=function(){
			var title 	= '向您打招呼了';
			var content = '向您打招呼了';
		
			if(uname==""){
				msg('非法参数！');
			}else{	
				var pras="op=poke&reciver="+uid+"&title="+title+"&content="+content+"&_r="+Math.random();
				({}).sendAjax("../space/message.php?"+pras,{
					onSuccess:function(){
					var result_msg=parseReturnMsg(this.responseXML);
					if(result_msg.status=='ok'){
							msg('打招呼成功，TA登录后会收到招呼！');
						}
						else{
							msg(result_msg.description);
						}
					},
					onFailure:function(){msg('打招呼出错了！')}
				});
			}
		}
		contentstr='<div class="dzh"><div class="floatLeft"><img src="'+logo+'" /></div><p><br />您将要向'+uname+'打招呼。</p><ul><li><p>'+uname+'将会在登录后收到招呼。<br /></p><br /><br /><br /><br /><br /></li></ul></div>';
		w.content(contentstr);
		w.title("打招呼")
		w.width(400)
		w.add_bt({"value":"确定","type":"button","echo":send_msg})
		w.add_bt({"value":"取消","type":"button"})
		w.show()	
		w.height()
	}
	show(uid,uname,logo);
}

/*以下为新增******************/

//输入框提示功能
function showInputTip(obj,inputValue,tipColor,inputColor){
	if(obj.value==inputValue) obj.value = "";
	obj.select();
	obj.style.color = inputColor || "#000";
	obj.onblur = function(){
		if(this.value == ""){
			this.value = inputValue || "";
			this.style.color = tipColor || "#000";
		}
	}
}

//字符处理;
//去左右空格; 
function trim(s){
 	return rtrim(ltrim(s)); 
}
//去左空格; 
function ltrim(s){
 	return s.replace( /^\s*/, ""); 
} 
//去右空格; 
function rtrim(s){ 
 	return s.replace( /\s*$/, ""); 
}
//验证信息;
//空字符值; 
function isEmpty(s){
	s = trim(s); 
	return s.length == 0; 
}
//Email;
function isEmail(s){
	s = trim(s); 
 	var p = /^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.){1,4}[a-z]{2,3}$/i; 
 	return p.test(s);
}
//数字; 
function isNumber(s){
	return !isNaN(s); 
}
//颜色值; 
function isColor(s){ 
	s = trim(s); 
	if (s.length !=7) return false; 
	return s.search(/\#[a-fA-F0-9]{6}/) != -1; 
}
//手机号码; 
function isMobile(s){ 
	s = trim(s); 
	var p = /(13|15)\d{9}/; 
	return p.test(s);
}
//身份证;
function isCard(s){ 
	s = trim(s); 
	var p = /^\d{15}(\d{2}[xX0-9])?$/; 
	return p.test(s);
}
//URL;
function isURL(s){
	s = trim(s).toLowerCase();
	var p = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
	return p.test(s);
}
//Phone;
function isPhone(s){
	s = trim(s);
	var p = /^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/;
	return p.test(s);
}
//Zip;
function isZip(s){
	s = trim(s);
	var p = /^[1-9]\d{5}$/;
	return p.test(s);
}
//Double;
function isDouble(s){
	s = trim(s);
	var p = /^[-\+]?\d+(\.\d+)?$/;
	return p.test(s);
}
//Integer;
function isInteger(s){
	s = trim(s);
	var p = /^[-\+]?\d+$/;
	return p.test(s);
}
//English;
function isEnglish(s){
	s = trim(s);
	var p = /^[A-Za-z]+$/;
	return p.test(s);
}
//中文;
function isChinese(s){
	s = trim(s);
	var p = /^[\u0391-\uFFE5]+$/;
	return p.test(s);
}
//双字节
function isDoubleChar(s){
	var p = /^[^\x00-\xff]+$/;
	return p.test(s);
}
//含有中文字符
function hasChineseChar(s){
	var p = /[^\x00-\xff]/;
	return p.test(s);
}
function hasAccountChar(s){
	var p = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,15}$/;
	return p.test(s);
}
function limitLen(s,Min,Max){
	s=trim(s);
	if(s=="") return false;
	if((s.length<Min)||(s.length>Max))
		return false;
	else
		return true;
}

//转义标签
function changeTag(s){
	s = s.replace(/</ig,"&lt;");
	s = s.replace(/>/ig,"&gt;");
	return s;
}

//返回含字符长度，中文算两个
function getCnLen(s){
	var chineseCount=0;
	for(var i=0;i<s.length;i++){
		if(isChinese(s.charAt(i)))
			chineseCount++;
	}
	return s.length+chineseCount;
}

/*自动完成功能******************/
var autoSelect={
	autoSelect_timeFlag:null,
	inputFocus:function(id){
		$.$(id).focus();		
	},
	startSelect:function(obj,selectListId,ajaxId,ajaxUrl){		//输入搜索内容的input的对象,自动搜索结果容器的id,生成ajax对象的DOM的id,ajax传送的url
		var autoSelectList=$.$(selectListId);	
		clearTimeout(this.autoSelect_timeFlag);
		obj.style.width=20+10*obj.value.length+"px";
		this.autoSelect_timeFlag=setTimeout(sendStr,300);
		window.document.onclick=function(){
			autoSelectList.style.display="none";
			obj.style.width="1px";
			obj.value="";
		}
		function sendStr(){
			autoSelectList.style.display="block";
		//	autoSelectList.innerHTML="<li style='padding:5px;'>loading...</li>";
			var myAjax=$.appfn(ajaxId);
			autoSelectList.style.height="auto";
			myAjax.sendAjax(ajaxUrl+obj.value,{
				onSuccess:function(){
					if(this.responseText){
						autoSelectList.innerHTML=this.responseText;						
						autoSelectList.style.overflowX="hidden";
						if(autoSelectList.offsetHeight>150){
							autoSelectList.style.height="150px";
							autoSelectList.style.overflowY="auto";	
						} else {
							autoSelectList.style.height=autoSelectList.childNodes.length*25+"px";	
						}
					} else {
						autoSelectList.innerHTML="<li style='padding:5px;'>无匹配结果！</li>"	
					}
				},
				onFailure:function(){msg('连接数据库失败,请重试！');}
			});
		}	
	},
	addInputValue:function(obj,toHiddenInputValue){		//onclick事件的对象，返回给hiddenInput的值，输入框的id,hiddenInput的id
		var input=$.$($.$("inputId").value);
		var inputWrapper=input.parentNode;
		input.value="";
		if(inputWrapper.innerHTML.indexOf(obj.innerHTML)!=-1) return;
		var inputStr='<li><input name="r_name" id="r_name" style="width:auto;float:left;" type="text" onkeyup="autoSelect(this);" /></li>';
		var newNode=document.createElement("li");
		newNode.className="selectedInfor";
		newNode.innerHTML=obj.innerHTML+'<input type="button" class="select_shutBtn" onmouseover="this.style.backgroundPosition=\'0px 100%\';" onmouseout="this.style.backgroundPosition=\'0px 0px\';" onclick="autoSelect.shutThisBtn(this,'+toHiddenInputValue+')" />';
		inputWrapper.insertBefore(newNode,input);
		$.$($.$("hiddenInputId").value).value+=toHiddenInputValue+",";		
	},
	shutThisBtn:function(obj,delHiddenInputValue){
		obj.parentNode.parentNode.removeChild(obj.parentNode);
		$.$($.$("hiddenInputId").value).value=$.$($.$("hiddenInputId").value).value.replace(delHiddenInputValue+",","");
	}
}

/*PNG透明*****************/
// correctly handle PNG transparency in Win IE 5.5 or higher.
function correctPNG() 
{   
    for(var i=0; i<document.images.length; i++)    
    {    
        var img = document.images[i]    
        var imgName = img.src.toUpperCase()    
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG")    
        {    
           
		   var imgID = (img.id) ? "id='" + img.id + "' " : ""   
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""   
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "   
            var imgStyle = "display:inline-block;" + img.style.cssText    
            var imgAttribs = img.attributes;    
            for (var j=0; j<imgAttribs.length; j++)    
            {    
                var imgAttrib = imgAttribs[j];    
                if (imgAttrib.nodeName == "align")    
                {    
                    if (imgAttrib.nodeValue == "left") imgStyle = "float:left;" + imgStyle    
                    if (imgAttrib.nodeValue == "right") imgStyle = "float:right;" + imgStyle    
                    break   
                }    
            }    
            var strNewHTML = "<span " + imgID + imgClass + imgTitle    
            strNewHTML += " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"   
            strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"   
            strNewHTML += "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"   
            img.outerHTML = strNewHTML    
            i = i-1    
        }    
    }    
}
if (document.all) {
	window.attachEvent("onload", correctPNG);
}	

function imgCorrectPNG(obj) 
{  
        var img = obj;    
        var imgName = img.src.toUpperCase()    
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG")    
        {    
		   var imgID = (img.id) ? "id='" + img.id + "' " : ""   
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""   
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "   
            var imgStyle = "display:inline-block;" + img.style.cssText    
            var imgAttribs = img.attributes;    
            for (var j=0; j<imgAttribs.length; j++)    
            {    
                var imgAttrib = imgAttribs[j];    
                if (imgAttrib.nodeName == "align")    
                {    
                    if (imgAttrib.nodeValue == "left") imgStyle = "float:left;" + imgStyle    
                    if (imgAttrib.nodeValue == "right") imgStyle = "float:right;" + imgStyle    
                    break   
                }    
            }    
            var strNewHTML = "<span " + imgID + imgClass + imgTitle    
            strNewHTML += " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"   
            strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"   
            strNewHTML += "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"   
            img.outerHTML = strNewHTML    
        }    
   
}

/*按钮的两态****************/
function changeBtnBackground(obj){
	obj.style.backgroundPosition="0 100%";
	obj.onmouseout=function(){
		obj.style.backgroundPosition="0 0";	
	}
}


//===========================点击修改内容函数====================================

function changeContent(obj,strNum,oEvent,oWidth,oneLine,blurSave){	
    if(obj.getElementsByTagName("input").length>0) return;
    function isChinese(s){
        var p = /^[\u0391-\uFFE5]+$/;
        return p.test(s);
    }	
    var textOld=obj.innerHTML;
    if(!blurSave){
        if(oneLine){
            obj.innerHTML="<input type='text' style='width:220px;height:20px' value='"+obj.innerHTML.replace( /^\s*/, "").replace( /\s*$/, "")+"' /> <input type='button' value='保存' class='sendBtn2' style='padding:0px;' /> <input type='button' value='取消' class='sendBtn2' style='padding:0px;' />";
            var save=obj.getElementsByTagName("input")[1];
            var cancel=obj.getElementsByTagName("input")[2];
        } else {
            obj.innerHTML="<textarea style='width:250px;height:50px;'>"+obj.innerHTML.replace( /^\s*/, "").replace( /\s*$/, "")+" </textarea><br /> <input type='button' value='保存' class='sendBtn2' style='padding:0px;' /> <input type='button' value='取消' class='sendBtn2' style='padding:0px;' />";	
            var save=obj.getElementsByTagName("input")[0];
            var cancel=obj.getElementsByTagName("input")[1];
        }
    }else{
        if(oneLine){
            obj.innerHTML="<input type='text' style='width:220px;height:20px' value='"+obj.innerHTML.replace( /^\s*/, "").replace( /\s*$/, "")+"' />";
        } else {
            obj.innerHTML="<textarea style='width:250px;height:50px;'>"+obj.innerHTML.replace( /^\s*/, "").replace( /\s*$/, "")+" </textarea>";	
        }
    }
    var text;	
    if(oneLine){
        text=obj.getElementsByTagName("input")[0];
    } else {
        text=obj.getElementsByTagName("textarea")[0];	
    }
    if(typeof oWidth == "number"){
        text.style.width=oWidth+"px";	
    }
    text.select();
    text.onclick=function(oevent){
        if(document.all) window.event.cancelBubble=true;
        else oevent.stopPropagation();	
    }
    if(!blurSave){
        save.onclick=function(oevent){
            if(text.value.replace( /^\s*/, "").replace( /\s*$/, "")==""){
                obj.innerHTML=textOld;
            }else{
                obj.innerHTML=text.value;
                obj.innerHTML=obj.innerHTML.replace(/</ig,"&lt;");
                obj.innerHTML=obj.innerHTML.replace(/>/ig,"&gt;");
                if(strNum){
                    for(var i=0;i<strNum;i++){
                        if(isChinese(obj.innerHTML.charAt(i))) strNum--;
                    }
                    obj.innerHTML=obj.innerHTML.substring(0,strNum);
                }
                if(typeof oEvent == "string"){
                    try	{eval(oEvent);}
                    catch (e) {}
                }
                if(typeof oEvent == "function"){
                    oEvent();
                }
                if(document.all) window.event.cancelBubble=true;
                else oevent.stopPropagation();
            }
            obj.style.background="transparent";
        }
        cancel.onclick=function(oevent){
            obj.innerHTML=textOld;
            obj.style.background="transparent";
            if(document.all) window.event.cancelBubble=true;
            else oevent.stopPropagation();	
        }
    }else{
        text.onblur=function(){
            if(text.value.replace( /^\s*/, "").replace( /\s*$/, "")==""){
                obj.innerHTML=textOld;
            }else{
                obj.innerHTML=text.value;
                obj.innerHTML=obj.innerHTML.replace(/</ig,"&lt;");
                obj.innerHTML=obj.innerHTML.replace(/>/ig,"&gt;");
                if(strNum){
                    for(var i=0;i<strNum;i++){
                        if(isChinese(obj.innerHTML.charAt(i))) strNum--;
                    }
                    obj.innerHTML=obj.innerHTML.substring(0,strNum);
                }
                if(typeof oEvent == "string"){
                    try	{eval(oEvent);}
                    catch (e) {}
                }
                if(typeof oEvent == "function"){
                    oEvent();
                }
            }
            obj.style.background="transparent";
        }
    }
}

function switchNav(obj, callback) {
    alert (obj.parentNode.parentNode.childNodes)
    callback();
}

function mp_open(albumid , musichost , musicid , type , mid) { // MP3播放器
    if(typeof mid == "undefined")
    {
        mid = "";
    }

    var w = 980;
    var h = 622;
    var s = 0;
    var target;
    var url;
    if (type == "yk")
    {
        target = "w_yuekuplayer";
        url = "http://music.sina.com.cn/yueku/m/" + mid + ".html";
    } else if (type == 'other') {
        url = albumid;
    } else if (type == 'multi' ) {
        target = "_player";
        url = "/space/player.php?op=multiplayer&musicStage="+musicid;
    } else {
        target = "_player";
        //url = "/space/music.php?op=player&ownerId="+albumid+"&musichost="+musichost+"&musicid="+musicid+"&type="+type+"&mid="+mid;
        url = "/space/player.php?op=player"+"&musicid="+musicid;
    }
    
    var left=(screen.width-w)/2;
    var top=(screen.height-h)/2;
    var r = window.open(url,target,'width='+w+',height='+h+',top='+top+',left='+left+',scrollbars=0,resizable=1,status='+s);
    r.focus();
    return r;   
}

var FrameP = new RegExp("/htapp/index.php");
var Frender = true;

if (window.parent) {

  if (!FrameP.test(window.location) ) {
      if (FrameP.test(window.parent.location)) {
          Frender = false;
	
      }
  }
}

function myAddBookmark(title,url) {
    if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function'))
    {
        window.sidebar.addPanel(title,url,"");
    }
    else
    {
        window.external.AddFavorite(url,title);
    }
}

function disObjIfNone(objId) {
    var obj = document.getElementById(objId)
    if (obj.style.display== 'none') {
        obj.style.display=''
    } else {
        obj.style.display= 'none'
    }
}

function mysendFlower(id) {

    var w=new _$w();
    var myAjax=$.appfn("flower_"+id);
    var ajaxUrl="/space/music.php?op=sendFlower&musicid="+id;
    
    myAjax.sendAjax(ajaxUrl,{
        onSuccess:function(){
            var msg_result=parseReturnMsg(this.responseXML);
            if(msg_result.status=="ok"){
                var fo = document.getElementById('flower_'+id)
                fo.innerHTML = parseInt(fo.innerHTML)+1
                msg('赠送鲜花成功！');
            }else{
                msg(msg_result.description);
            }
        },
        onFailure:function(){msg('更新失败,请重试')}
    });

}

