var focusControl=function(e){
	e.className="input_focus";
}
var blurControl=function(e){
	e.className="input_blur";
}
var expes=new Object();
window.addEvent('domready',function(){
	//init
	var re = /a_(\w+)/;
	var arr={};
	$$('.e').each(function(i){
		var m = re.exec(i.className);
        if (m) {
            eval("expes.init"+m[1]+"();");
        }
	});
	prettifyControl();
});
var prettifyControl=function (){
	var pageforms=document.forms;
	form_count=pageforms.length;
	//set input textarea submit styles
	for(var i=0;i<form_count;i++){
		var form_id=pageforms[i].id;
		var inputControls=$(form_id).getElements('input[type=text]');
		inputControls.each(function(inputControl){
			inputControl.className="input_blur";
			inputControl.addEvent('focus',function(){focusControl(inputControl)});
			inputControl.addEvent('blur',function(){blurControl(inputControl)});
		});
		var inputControl1s=$(form_id).getElements('input[type=password]');
		inputControl1s.each(function(inputControl1){
			inputControl1.className="input_blur";
			inputControl1.addEvent('focus',function(){focusControl(inputControl1)});
			inputControl1.addEvent('blur',function(){blurControl(inputControl1)});
		});
		var textareas=$(form_id).getElements('textarea');
		textareas.each(function(textarea){
			textarea.className="input_blur txt_area";
			textarea.addEvent('focus',function(){textarea.removeClass("input_blur");textarea.addClass("input_focus");});
			textarea.addEvent('blur',function(){textarea.removeClass("input_focus");textarea.addClass("input_blur");});
		});
	}
	//set delete link confirm
	var delete_links=$('main').getElements('a[rel^=delete]');
	delete_links.each(function(delete_link){
		var confirmString=delete_link.getProperty('rel').replace('delete','');
		if(confirmString==''){
			confirmString="确定删除吗?";
		}else{
			confirmString=confirmString.replace('|','');
		}
		delete_link.addEvent('click', function(e){
			return confirm(confirmString);
		});
		//delete_link.setProperty('onclick','return confirm(\''+confirmString+'\');');
	});
}
var loading=function(el){
	el.setStyle('display','none');
	var load = (new Element('span',{id:'loading'})).inject(el,'before');
	load.set('html','<img src=\"/image/ajax-loader.gif\"> loading</span>');
}
var stopLoading=function(el){
	el.setStyle('display','inline');
	$('loading').dispose();
}
expes.initSearchText=function(){
	setTip();
	$('i_focus').addEvent('focus',function(){
		if($('i_focus').title==$('i_focus').value){
			$('i_focus').value='';
		}
	});
	$('i_focus').addEvent('blur',function(){
		if(!$('i_focus').value){
			$('i_focus').value=$('i_focus').title;
		}
	});
	$('arrow').addEvent('click',function(){
		if($$('.arrow_down').getStyle('display')=='none'){
			hideSearchMenu();
		}else{
			showSearchMenu();
		}
	});
	$('arrow').addEvent('mouseover',function(){
		this.setProperty('rel','on');
	});
	$('arrow').addEvent('mouseout',function(){
		this.setProperty('rel','off');
	});
	$('body').addEvent('mousedown',function(){
		if($('arrow').getProperty('rel')!='on'){
			hideSearchMenu();
		}
	});
	$$('.search_b').addEvent('click',function(){
		var keyword=$('i_focus').value==$('i_focus').title?'':$('i_focus').value;
		window.location.href='/search/all/'+keyword;
	});
	var els=$('s_menu').getElements('a');
	els.each(function(el){
		el.addEvent('click',function(){
			var keyword=$('i_focus').value==$('i_focus').title?'':$('i_focus').value;
			window.location.href=this.rel+keyword;
		});
	});
}
var showSearchMenu=function(){
	$$('.arrow_down').setStyle('display','none');
	$$('.arrow_up').setStyle('display','inline');
	$('s_menu').setStyle('display','inline');
}
var hideSearchMenu=function(){
	$$('.arrow_down').setStyle('display','inline');
	$$('.arrow_up').setStyle('display','none');
	$('s_menu').setStyle('display','none');
}
var setTip=function(){
	if($('i_focus')){
		$('i_focus').addClass('grey');
		$('i_focus').value=$('i_focus').title;
	}
}

expes.initBadinfoReportDialog=function(){
	$('report_c').addEvent('click',function(){
		showDialog(null);
		var jsonRequest = new Request.JSON({url: '/json.php?r=bad_info_type', onComplete: function(jsonObj){
			var types=jsonObj.types;
			var str='';
			types.each(function(type) {
				str+='<input name="reason" type="radio" value="'+type.id+'"> '+type.type+'<br>';
			});
			$('dialog').set('html',dialogCloseStr('举报这个页面')+'<form id="infoform" action="/bad_info_report" method="post"><div style="padding:0 10px;"><span id="tip">请选择举报这个页面的原因</span><br>'+str+'<div style="padding:10px 0;"><input type="submit" class="submit" value="举报"></input></div></div></form>');
			setOverlay();
			window.addEvent("domready",function(){
				$("infoform").addEvent("submit",function(e){
					var rad = $("infoform").getElements('input[type=radio]');
					var ok = false;
					rad.each(function(e,i){
						if(e.checked){
							ok = true;
						}
					});
					if(!ok){
						$('tip').setStyle('color','red');
						return false;
					}else{
						new Event(e).stop();
						$("infoform").set('send',{onComplete:function(){
							if(this.response.text.contains("true")){
								$('dialog').set('html','<h2 style="text-align:center">举报成功</h2>');
								setOverlay();
								$('dialog','overlay').fade();
								setTimeout(closeDialog, 1000);
							}else{

							}
						}}).send();
					}
				});
			});
		}}).get();
	});
}
expes.initSetInfoGather=function(){
	var albumReg = /(.)+(flickr|footbig|yupoo|bababian|picasa){1}(.)+/;
	var mbProvider;
	var rad = $("myform").getElements('input[type=radio]');
	$('myform').setProperty('onsubmit','return true;');
	$('myform').addEvent('submit',function(e){
		if($('album').value.trim()!=''&&$('album').value.trim()!='http://'){
			if(!albumReg.exec($('album').value)){
				$('album_tip').set('html','地址不正确');
				$('album_tip').fade(1);
				return false;
			}else{
				$('album_tip').set('html','');
				$('album_tip').fade();
			}
		}else{
			$('album_tip').set('html','');
			$('album_tip').fade();
		}
		rad.each(function(e,i){
			if(e.checked){
				mbProvider=e.value;
			}
		});
		if(mbProvider!=""&&$('microblog_id').value==""){
			$('mb_tip').set('html','请输入你的ID');
			$('mb_tip').fade(1);
			return false;
		}else{
			$('mb_tip').set('html','');
			$('mb_tip').fade();
		}
		new Event(e).stop();
		loading($('myform').getElements('input[type=submit]')[0]);
		$("myform").set('send',{onComplete:function(){
			stopLoading($('myform').getElements('input[type=submit]')[0]);
			if(this.response.text=="1"){
				rt_success($('last_el'),'修改成功');
			}else{
				rt_success($('last_el'),'未做任何修改');
			}
		}}).send();
	});
}
expes.initUpdatePassword=function(){
	$('password').addEvent('blur',function(){
		checkPassword(1);
	});
	$('repassword').addEvent('blur',function(){
		checkPassword(1);
	});
	$("myform").addEvent("submit",function(e){
		if(checkPassword(1)){
			new Event(e).stop();
			loading($('myform').getElements('input[type=submit]')[0]);
			this.set('send',{onComplete:function(){
				stopLoading($('myform').getElements('input[type=submit]')[0]);
				if(this.response.text=="1"){
					rt_success($('tips'),'修改成功');
				}else if(this.response.text=="0"){
					rt_success($('tips'),'未做任何修改');
				}else{
					rt_success($('tips'),'未修改'+this.response.text);
				}
			}}).send();
		}else{
			return false;
		}
	});
}
expes.initSetBroadcast=function(){
	$("myform").addEvent("submit",function(e){
		new Event(e).stop();
		loading($('myform').getElements('input[type=submit]')[0]);
		this.set('send',{update:$("tips"),onComplete:function(){
			stopLoading($('myform').getElements('input[type=submit]')[0]);
			if(this.response.text=="1"){
				rt_success($('tips'),'设置成功');
			}else{
				rt_success($('tips'),'没做任何修改');
			}
		}}).send();
	});
}
expes.initMailDialog=function(){
	$$('.a_MailDialog').addEvent('click',function(){
		showDialog(dialogCloseStr('发短消息')+'<form id="myform" action="/u/mail/write/to'+this.getProperty('rel')+'_act" method="post"><div style="text-align:center;"><textarea rows="6" class="input_blur" style="width:500px; overflow:auto; height:100px;" id="mail_content" name="mail_content"></textarea></div><div class="block100"><div style="height:30px;text-align:center;"><input type="submit" value="发送"></input></div></div></form>');
	});
}
expes.initAddFriendDialog=function (to,title,withmail){
	$$('.addfriend').each(function(i){
		i.addEvent('click',function(){
			var mailStr;
			if(i.getProperty('ref')=="1"){
				mailStr='<p><textarea class="input_blur" style="width:95%; height:80px;" id="mail" name="mail"></textarea><br>(可以不填)</p>';
			}else{
				mailStr='';
			}
			var addStr='<div style="padding:0 10px;"><form id="new_topic_form" action="/u/'+this.getProperty('rel')+'/as_friend_act" method="post">'+mailStr+'<p>标签 <input type="text" id="tag" name="tag" class="input_blur" style="width:100px;" value=""></input>(只能用一个)</p>$used_tags$<p><input name="friend_type" type="checkbox"></input>私密好友</p><p><input type="submit" value="添加"></input></p></form></div>';
			showDialog(null);
			var jsonRequest = new Request.JSON({url: '/expes.php?r=friend_tag_json', onComplete: function(jsonObj){
				var tags=jsonObj.friend_tag;
				var tagStr='';
				var tagCount=tags.length;
				if(tagCount>0){
					tagStr+='<p>已有标签:';
					tags.each(function(tag) {
						var tagID=tag.id;
						var tagText=tag.tag;
						tagStr+=' <a href="#" id="tag'+tagID+'" onclick="$(\'tag\').value=$(\'tag'+tagID+'\').get(\'text\');">'+tagText+'</a> ';
					});
					tagStr+='</p>';
				}
				addStr=addStr.replace('$used_tags$',tagStr);
				$('dialog').set('html',dialogCloseStr('加为好友')+addStr);
				setOverlay();
			}}).get();
		});
	});
}
expes.initEditFriend=function (){
	$$('.editfriend').each(function(i){
		i.addEvent('click',function(){
			var editStr='<form id="myform" method="post" action="/u/friend/'+i.getProperty('rel')+'/edit_act"><div class="user_list" style="width:23%; float:left;text-align:center;"><a href="/u/'+i.getProperty('rel')+'">$portrait$<br>$nick$</a></div><div style="border-left:1px dotted #ccc; padding-left:10px;margin-left:10px; width:69%; float:left; height:200px;">标签 <input type="text" id="tag" name="tag" class="input_blur" style="width:100px;" value="$tag$"></input>(只能使用一个)<br><br>已有标签: $used_tags$<br><br><input name="friend_type" type="checkbox"$check$></input> 私密<br><br><input type="submit" class="submit" value="修改"></input></div></form>';
			showDialog(null);
			var jsonRequest = new Request.JSON({url: '/expes.php?r=friend_json&fid='+i.getProperty('rel'), onComplete: function(jsonObj){
				var friend=jsonObj.friend;
				var tag=friend[0].tag;
				var nick=friend[0].nick;
				var portrait=friend[0].portrait;
				var checked='';
				if(friend[0].type=="1"){
					checked='checked';
				}
				editStr=editStr.replace('$portrait$',portrait);
				editStr=editStr.replace('$tag$',tag);
				editStr=editStr.replace('$nick$',nick);
				editStr=editStr.replace('$check$',checked);
				var tags=jsonObj.friend_tag;
				var tagStr='';
				tags.each(function(tag) {
					var tagID=tag.id;
					var tagText=tag.tag;
					tagStr+=' <a href="#" id="tag'+tagID+'" onclick="$(\'tag\').value=$(\'tag'+tagID+'\').get(\'text\');">'+tagText+'</a> ';
				});
				editStr=editStr.replace('$used_tags$',tagStr);
				$('dialog').set('html',dialogCloseStr('修改好友')+editStr);
				setOverlay();
			}}).get();
		});
	});
}
expes.initInviteUser=function(){
		$("myform").addEvent("submit",function(e){
			new Event(e).stop();
			var emails=$('email').value.split(',');
			var count=emails.length;
			res = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
			var ok=true;
			for (i=0;i<count;i++){
				if(emails[i].length>0&&!res.test(emails[i])){
					$('rt').setStyle('display','block');
					$('rt').set('html','请填写正确的Email，并将多个Email用半角逗号隔开');
					ok=false;
				}
			}
			if(ok==true){
				$('rt').setStyle('display','none');
				$('invite_submit').setProperty('disabled','disabled');
				$('invite_submit').setProperty('value','正在发送...不要关闭该页面');
				$("myform").set('send',{onComplete:function(){
					$('invite_submit').setProperty('onsubmit','return true;');
					$('invite_submit').setProperty('value','已发送');
					rt_success($('rt'),'成功发送给了'+this.response.text+'个朋友')
				}}).send();
			}
		});
}
expes.initDeleteMsg=function(){
	$$('.dlt').each(function(el){
		el.addEvent('click',function(){
			var url='/u/message/'+this.getProperty('rel')+'/delete';
			ajaxDelete($(this.getProperty('rel')),url);
		});
	});
}
expes.initNewING=function(){
	$('myform').setProperty('onsubmit','return true;');
	$('myform').addEvent('submit',function(e){
		new Event(e).stop();
		check_post(150);
		if(check_post(150)){
			loading($('myform').getElements('input[type=submit]')[0]);
			$('myform').set('send',{onComplete:function(){
				var start=this.response.text.indexOf('$');
				$('content').value='';
				stopLoading($('myform').getElements('input[type=submit]')[0]);
				//if($('ings')){
					//$('ings').set('html',this.response.text.substring(start+1));
				//}else{
					window.location.reload();
				//}
			}}).send();
		}else{
			return false;
		}
	});
}
expes.initDltBC=function(){
	$$('.oper').each(function(el){
		el.addEvent('click',function(){
			var id=el.getProperty('rel');
			var url='/u/broadcast/'+id+'/delete';
			ajaxDelete($(id),url);
		});
	});
}
expes.initDltRecommend=function(){
	$$('.oper').each(function(el){
		el.addEvent('click',function(){
			var id=el.getProperty('rel');
			var url='/u/recommend/'+id+'/delete';
			ajaxDelete($(id),url);
		});
	});
}
var uploadAndRedirect=function(){
	$('myform').setProperty('onsubmit','return true;');
	$('myform').addEvent('submit',function(){
		loading($('myform').getElements('input[type=submit]')[0]);
		this.upload().addEvent('onFinish',function(){
			stopLoading($('myform').getElements('input[type=submit]')[0]);
			if(this.responseText.contains("true")){
				$('rt').fade();
				window.location.href=this.responseText.substr(5);
			}else{
				$("rt").set('html',this.responseText);
				$('rt').fade(1);
			}
		});
		return false;
	});
}
var zoomPic=function(){
	var topicImages=$('topic').getElements('img');
	topicImages.each(function(topicImage){
		if(topicImage.width>500){
			newWidth="500px";
			newHeight=Math.round(500*topicImage.height/topicImage.width)+"px";
			//topicImage.setProperties({width:newWidth,height:newHeight});
			topicImage.setStyle('width',newWidth);
		}
	});
	var postImages=$('post').getElements('img');
	postImages.each(function(postImage){
		if(postImage.width>500){
			newWidth="500px";
			newHeight=Math.round(500*postImage.height/postImage.width)+"px";
			//postImage.setProperties({width:newWidth,height:newHeight});
			postImage.setStyle('width',newWidth);
		}
	});
}
//ajax upload
var AjaxUpload = new Class({
	initialize: function(form,url,data){
		this.form = $(form);
		if(this.form.get('tag')!='form'){
			alert('is not form');
			this.form = null;
			return this;
		}
		this.form.getAttribute('action')||this.form.Attribute('action',url);
		this.processId = 'ajaxupload_'+Math.floor(Math.random()*10000);
		this.target = (new Element('iframe',{
			styles:{width:0,height:0,border:0,visibility:'hidden',position:'absolute'},
			name: this.processId,
			id:   this.processId,
			src:  'about:blank'
		})).inject(document.body);
		this.form.setProperty('target',this.processId);
		this.appendElements = [];
		this.appendElements.push(this.target);
		this.appendData({ajax:1});
		this.appendData(data);
	},
	appendData:function(data){
		if($type(data)=='string'){
			var value = data.split('&');
			data = {};
			for(var i=0; i < value.length; i++){
				var pos = value[i].indexOf('=');
				data[value[i].substring(0,pos)] = value[i].substring(pos+1);
			}
		}
		for(var key in data){
			this.appendElements.push(
			(new Element('input',{
				type:'hidden',
				name:key,
				value:data[key]
			})).inject(this.form));
		}
	},
	upload:function(){
		try{
			this.form.submit();
		}catch(e){
			return this.onError(e);
		}
		this.timer = (function(){
			try{
				var doc = this.target.contentWindow.document||this.target.contentDocument;
				if(!doc) return;
				var location = window.opera ? this.target.location : doc.location;
			}catch(e){
				this.timer = $clear(this.timer);
				return this.onError(e);
			}
			if(!location||location=='about:blank'){
				return;
			}else{
				this.timer = $clear(this.timer);
				this.responseText = doc.body?doc.body.innerHTML:doc.documentElement.textContent;
				this.responseXML  = doc.XMLDocument||doc;
				this.fireEvent('onFinish',[this.responseText,this.responseXML]);
				this.cancel();
			}
		}).periodical(window.opera ? 150 : 100,this);
		return this;
	},
	onError:function(error){
		this.fireEvent('onError',error);
		this.fireEvent('onFinish',null);
		this.cancel();
		return this;
	},
	cancel:function(){
		$clear(this.timer);
		this.target.location = 'about:blank';
		//this.appendElements.forEach(function(el){el.remove();});
	}
});
AjaxUpload.implement(new Events);
Element.implement({
	upload:function(){
		return new AjaxUpload(this).upload();
	}
});
function rt_success(el,text){
	if ($("success")==null){
		var newDiv=new Element('div', {id: 'success'});
		newDiv.inject(el,'after');
	}else {
		$("success").fade('in');
	}
	$("success").addClass("success");
	$("success").set('html',text);
	(function(){$("success").fade()}).delay(1500);
	(function(){$("success").dispose()}).delay(2000);
}


function show_and_redirect(){
	if(this.responseText.contains("true")){
		window.location.href=this.responseText.substr(5);
	}else{
		$('errors').addClass("n_error");
		$("errors").set('html',this.responseText);
		$("ajax_upload_submit").set('html',"");
	}
}
function check_topic(){
	if($("title").value.trim()==""||$("title").value.length>100){
		$("tips").set('html',"标题不能为空且长度不能超过100个字符!");
		return false;
	}else if($("content").value.trim()==""||$("content").value.length>10000){
		$("tips").set('html',"内容不能为空且长度不能超过10000个字符!");
		return false;
	}else{
		return true;
	}
}
var check_post=function(maxLength){
	if($("content").value.trim()==""){
		$("tips").set('html',"请输入一些东西!");
		return false;
	}else if($("content").value.length>maxLength){
		$("tips").set('html',"太长了，只能容纳"+maxLength+"个字符!");
		return false;
	}else{
		$("tips").set('html',"");
		return true;
	}
}

var showDialog = function(div) {
	if($('dialog')!=null) return;
	var overlay  = new Element('div', {id: 'overlay'});
	var dialog  = new Element('div', {id: 'dialog'});
	overlay.inject($('body'),'bottom');
	dialog.inject($('body'),'bottom');
	var overlay  = new Element('div', {id: 'all'}).inject($('body'),'bottom');
	if(div != null){
		$('dialog').set('html',div);
	}else{
		$('dialog').set('html',dialogCloseStr('正在载入')+"<div class='loadpop'>&nbsp;<img src='/image/ajax-loader.gif' align='absmiddle'>&nbsp;正在载入，请稍候...</div>");
	}
	setOverlay();

}

var dialogCloseStr=function(title){
	return "<div id='closelink'><span class=\"title\" style='float:left;text-align:left;width:95%;'>"+title+"</span><span onclick='closeDialog();' style='float:right;width:5%;'>X</span></div><br>";
}
var setOverlay = function(){
	var oheight = (Browser.Engine.trident?-2:17);
	$('overlay').setStyle('height',$('dialog').offsetHeight+oheight);
}

var closeDialog = function(){
	if($('all')){
		$('all').dispose();
	}
	$('dialog').dispose();
	$('overlay').dispose();
	return false;
}

var toggle_intro=function(skin){
	var img=$('toggle_img').getProperty('src');
	var full_intro=$('p_full').get('html');
	var short_intro=$('p_short').get('html');
	if(img.contains('expand')){
		$('p_intro').set('html',full_intro);
		$('toggle_img').set('src','/image/'+skin+'/collapse.gif');
	}else{
		$('p_intro').set('html',short_intro);
		$('toggle_img').set('src','/image/'+skin+'/expand.gif');
	}
}


var showVideo=function(vid){
	var thumb_div="thumb"+vid;
	var video_div="video"+vid;
	var playvideo_div="playvideo"+vid;
	var play_str=$(thumb_div).getProperty("name");
	$(video_div).setStyle('display','none');
	$(playvideo_div).setStyle('display','block');
	$(playvideo_div).set('html','<span>'+play_str+'</span> <span onclick="$(\''+video_div+'\').setStyle(\'display\',\'block\');$(\''+playvideo_div+'\').set(\'html\',\'\');" style="cursor:pointer;">缩进</span>');
}
var handleFriendGroupRequest=function(gid,fid,result){
	if (result==1){
		var url='/group/'+gid+'/friend/'+fid+'/accept';
	}else {
		var url='/group/'+gid+'/friend/'+fid+'/refuse';
	}
	var req = new Request.HTML({url:url,
	onSuccess: function(html) {
		$('request'+gid+fid).set('html','');
	},
	onFailure: function() {
	}
	});
	req.send();
}
var ajaxDelete=function(el,url){
	var rt=confirm('确定删除吗？');
	if(rt){
		var req = new Request.HTML({url:url,
		onSuccess: function(html) {
			el.fade();
			setTimeout(function(){el.dispose();}, 1000);
		},
		onFailure: function() {
		}
		});
		req.send();
	}
}
expes.initTabs=function(){
	var tabs=$('body').getElements('span[rel=tab]');
	var divs=$('body').getElements('div[rel=tabcontent]');
	var count=tabs.length;
	tabs.each(function(tab){
		tab.addEvent('click',function(){
			num=tab.getProperty('id');
			for(i=1;i<count+1;i++){
				contentID='tabcontent'+i;
				if(i.toString()==num){
					$(i.toString()).addClass('current');
					var tabhtml=$(i.toString()).get('html');
					tabhtml=tabhtml.replace(/<\/?.+?>/g,"");
					$(i.toString()).set('html','<span>'+tabhtml+'</span>');
					$(contentID).setStyle('display','block');
				}else{
					$(i.toString()).removeClass('current');
					var tabhtml=$(i.toString()).get('html');
					tabhtml=tabhtml.replace(/<\/?.+?>/g,"");
		
					$(i.toString()).set('html','<a href="javascript:void(0)">'+tabhtml+'</a>');
					$(contentID).setStyle('display','none');
				}
			}
			//contentID='tabcontent'+num;
		});
	});
}
var fanfouTip=function(){
	showDialog(null);
	$('dialog').set('html',dialogCloseStr('饭否用户提醒')+'<div style="padding:0 10px;">饭否用户，下面需要填写的微博客ID不是你登陆饭否用的用户名，而是你饭否主页网址的个性化部分，比如：你的饭否主页地址为http://fanfou.com/wanger 那么你在下面的微博客ID中应该填写 wanger </div>');
	setOverlay();
}