/*
* ajax post new
* fangxu 2011-10-13
*/
// 测试人列表
var BbsPost = {};
BbsPost.isWww4 = location.href.indexOf('http://www4.tianya.cn/') == 0;
BbsPost.href = location.pathname;
BbsPost.type = BbsPost.href.match(/\/publicforum\//gi) ? 'public' : BbsPost.href.match(/\/techforum\//gi) ? 'tech' : BbsPost.href.match(/\/tianyacity\//gi) ? 'city' : null;
BbsPost.ajaxPost = function (button, form) {
	//if (!isTestUsers()) {
	//	form.submit2.disabled = 'true';
	//	form.submit();
	//	return;
	//}
	jQuery(button).attr('disabled', 'true');
	var butValue = button.value;
	button.value = '载入中...';
	var params, userPwd = "";
	var obj = jQuery('#FormResponse');
	var item = BbsPost.type == 'public' ? obj.find('input[name=strItem]').val().toLowerCase() : obj.find('input[name=idItem]').val();
	var userId = __global.getUserId();
	var userName = __global.getUserName();
	var sso  = 'sso=' + __global.getCookie("sso");
	var user = 'user=w=' + __global.getUserName() + '&id=' + userId;
	var temp = 'temp=k=' + __global.getKey() + '&t=' + __global.getPartCookie("temp","t");
	var bCompose = BbsPost.href.indexOf('/Compose') > -1 || BbsPost.href.indexOf('/compose') > -1 ? true : false;
	var artId = obj.find('input[name=idArticle_bottom]').val();
	artId = (artId == '' || artId == undefined) ? obj.find('input[name=idArticle]').val() : artId;
	var flashUrl = obj.find('input[name=strFlashURL]').val();
	if (flashUrl == undefined) flashUrl = '';
	flashUrl = flashUrl == '在此输入视频链接' ? '' : flashUrl;
	// 处理 HTTP 开头的视频连接
	if (flashUrl.length > 0) flashUrl = flashUrl.replace(/^http:\/\//i, 'http://');
	if (userId == null || userName == null) {
		userId = 0;
		userName = jQuery("input[name=strWriter]").val();
		userPwd = jQuery("input[name=strPassword]").val();
	}
	var content = obj.find('textarea[name=strContent]').val();
	//content = content.replace(/(\r\n|\n\r|\r|\n)/gi, "\u9fb3");
	var contentHtml, userHtml, nameHtml;
	var pContentDiv = jQuery('#pContentDiv');
	params = "userId="+userId+"&userName="+encodeURIComponent(userName);
	if (userPwd != undefined && userPwd != '') params += "&userPwd=" + userPwd;
	params += "&userLogin="+encodeURIComponent(user + ';' + temp + ';' + sso);
	params += "&item=" + item + "&rowsetType=1&bCompose=" + bCompose;
	params += "&content=" + encodeURIComponent(content.replace(/(\r\n|\n\r|\r|\n)/gi, "\u9fb3"));
	if (bCompose) {
		var title = obj.find('input[name=strTitle]').val();
		obj.find('input[name=strKind]').each(function(i,item) {
			if (jQuery(item).attr('checked') == true) {
				if (jQuery(item).val() != '(原创)') {
					title += jQuery(item).val();
				}
				return;
			}
		});
		var subItem = obj.find('select[name=strSubItem]').val();
		subItem = !!subItem ? subItem : obj.find('select[name=wenhua]').val();
		subItem = (subItem == undefined || subItem == 'wangliang') ? '' : subItem;
		var arrApp = jQuery("#app-data span em[appurl=url]");
		var topicsIds = "";
		for (var i=0; i<arrApp.length; i++) {
			var appUrl = arrApp.eq(i).text();
			appUrl = jQuery.trim(appUrl);
			topicsIds += "," + appUrl;
		}
		topicsIds = topicsIds.slice(1);
		params += "&subItem=" + (subItem == undefined ?  '' : subItem);
		params += "&title=" + encodeURIComponent(title);
		params += "&flashUrl=" + encodeURIComponent(flashUrl);
		params += "&musicUrl=" + encodeURIComponent(obj.find('input[name=strMusicURL]').val());
		params += "&topicsIds=" + topicsIds;
		params += "&bOriginal=" + true; // bOriginal
	} else {
		params += "&articleId=" + artId;
		params += "&bWeiBo=" + (obj.find('input[name=weibo]').attr('checked') ? "true" : "false");
		params += "&flashUrl=" + encodeURIComponent(flashUrl); // 视频专区容许回复发布flash
		if (!!obj.find('input[name=validateCode2]').attr('tagName') && obj.find('input[name=validateCode2]').val() != '') {
			params += "&vCode=" + encodeURIComponent(obj.find('input[name=validateCode2]').val());
		}
	}
	//alert(obj.find('input[name=strFlashURL]').val());
	//alert(obj.find('input[name=strMusicURL]').val());
	//jQuery.getJSON("http://post.tianya.cn/compose.jsp?jsoncallback=?",
	var note = jQuery("#jb_note");
	if (!!note.attr('id')) {
		note.css("top", jQuery(button).position().top - 200);
		note.css("left", jQuery("body").width()/2 - note.width()/2);
	}
	var url = "/new/includes/fn_Post.asp";
	if (location.href.indexOf('http://www.tianya.cn/') == 0)
	{
		params += "&bFilterHtml=true";
		url = bCompose ? "http://www.tianya.cn/post/compose.jsp" : "http://www.tianya.cn/post/reply.jsp";
	}
	jQuery.ajax({
		type: "POST",
		cache: false,
		//timeout : 12000,
		dataType : "json",
		data: params,
		url: url,
		success: function(data, textStatus){
			var message = '';
			var showTime = 3000;
			if (data == null || !!data.error_msg) {
				message = (bCompose ? "发表" : "回复") + '失败['+(data == null ? 'data is null' : data.error_msg)+']';
			} else {
				if (bCompose) {
					if (data.id > 0) { // 帖子id
						showTime = 2000;
						message = '发表成功，积分+30';
						//if (confirm('发帖成功！帖子id=' + data.id + '\r\n是否跳转到您刚发布的帖子？')) {
							//window.location.href = BbsPost.getArtLink(item, data.id);
						//}
						setTimeout(function() {
							if (__global.getUserName() != '心在奔跑')
								window.location.href = BbsPost.getArtLink(item, data.id);
						}, showTime + 100);
					} else {
						message = 'error!' + item + ',' + data.id;
					}
				} else {
					if (data.msg == 'true') {
						showTime = 2000;
						message = '回复成功，积分+3';
						//nameHtml.appendTo(pContentDiv);
						//contentHtml.appendTo(pContentDiv);
						pContentDiv.append(BbsPost.getHtml(userId, userName, content));
						obj.find('textarea[name=strContent]').val('');
						obj.find('input[name=strFlashURL]').val(''); // 清空flash
						// 增加点击1
						//jQuery.get('http://click.tianyaui.com/clkme.jsp?item='+item+'&idArticle='+artId+'&cate=c&s='+Math.random());
					} else {
						message = 'error!' + item + ',' + params.articleId; // 帖子id
					}
				}
			}
			BbsPost.errorMsg(message, showTime, button, butValue);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//请求出错处理
			button.value = butValue;
			jQuery(button).removeAttr('disabled');
			BbsPost.errorMsg((bCompose ? "发表" : "回复") + "失败!请联系管理员!", 3000, button, butValue);
			//BbsPost.errorMsg((bCompose ? "发表" : "回复") + "失败!请联系管理员!\n错误代码:" + (!!XMLHttpRequest ? XMLHttpRequest.status : XMLHttpRequest), 3000);
		}
	});
}
BbsPost.getHtml = function (uId, uName, content) {
	var html = '';
	var color1 = '#f5f9fa';
	var color2 = 'green';
	var className = 'post';
	var style = '';
	if (BbsPost.type == 'public') {
		style = 'style="padding-top: 20px;"';
	} else if (BbsPost.type == 'tech') {
		if (BbsPost.isWww4) {
			style = 'style="padding-top: 20px;"';
			className = 'content';
			color2 = '#6699cc';
		}
	} else if (BbsPost.type == 'city') {
		if (BbsPost.isWww4) {
			style = 'style="padding-top: 20px;"';
			color1 = '#ffffff';
			className = 'content cf';
		}
	}
	content = BbsPost.getImageContent(content);
	content = content.replace(/(\r\n|\n\r|\r|\n)/gi, "<br>　　");
	content = ty_bbs_attention_action(0, null, content);
	html += '<table width="100%" cellspacing="0" border="0" bgcolor="'+color1+'" '+style+'><tbody>';
	html += '<tr><td style="color:'+color2+';text-align:center;font-size:13px;">';
	html += '作者：<a target="_blank" href="http://my.tianya.cn/name/'+uName+'" _userinfo="'+uId+','+uName+'" class="lnkChanged">'+uName+'</a>';
	html += '<span value="'+uId+'" name="ad_logo_userid_'+uId+'"></span>　回复日期：'+BbsPost.getPostDay()+'</font></td></tr></tbody></table>';
	html += '<div class="'+className+'">　　'+content+'</div>';
	return html;
}
BbsPost.errorMsg = function (message, time, button, butValue) {
	var note = jQuery("#jb_note");
	if (!!note.attr('id')) {
		if (message.length >= 29) {
			note.find("h2").css("font-size", "14px");
			note.find("h2").css("padding", "3px 5px 0");
		} else {
			note.find("h2").css("font-size", "16px");
			note.find("h2").css("padding", "14px 20px 0");
		}
		if (message.indexOf('发表失败') > -1 && message.indexOf('发表成功') > -1) {
			message = message.replace('发表失败', '');
		}
		note.find("h2").html(message);
		note.fadeIn('slow');
		setTimeout(function() {
			button.value = butValue;
			jQuery(button).removeAttr('disabled');
			note.fadeOut('slow');
		}, time);
	} else {
		alert(message);	
	}
}
/**
* 获得当前时间
*/
BbsPost.getPostDay = function () {
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	var date = now.getDate();
	var hour = now.getHours();
	var minute = now.getMinutes();
	var second = now.getSeconds();
	month = month < 10 ? '0' + month : month;
	date = date < 10 ? '0' + date : date;
	hour = hour < 10 ? '0' + hour : hour;
	minute = minute < 10 ? '0' + minute : minute;
	second = second < 10 ? '0' + second : second;
	return year+'-'+month+'-'+date+' '+hour+':'+minute+':'+second;
}
/**
* 获得帖子连接方法
*/
BbsPost.getArtLink = function (item, artId, page) {
	var link;
	page = !page ? 1 : page;
	if (BbsPost.type == 'public') {
		link ='http://www.tianya.cn/publicforum/content/'+item+'/1/'+artId+'.shtml';
	} else if (BbsPost.type == 'tech') {
		link = 'http://www.tianya.cn/techforum/content/'+item+'/'+page+'/'+artId+'.shtml';
	} else if (BbsPost.type == 'city') {
		link = 'http://bbs.city.tianya.cn/tianyacity/content/'+item+'/'+page+'/'+artId+'.shtml';
	}
	return link;
}
/**
* 过滤html代码，把图片地址转换成<img src= />
*/
BbsPost.getImageContent = function (content) {
	var newContent = content;
	if (newContent.indexOf('http://') > -1)
	{
		newContent = newContent.replace("<", "&lt;");
		newContent = newContent.replace(">", "&gt;");
		var reg = /(http\:\/\/[\w\.\/\-\%]+\.(jpg|gif|png|bmp|jpeg))(\r|\n|$|<br>)/gi;
		var arr = newContent.match(reg);
		if (arr != null) {
			if (arr.length > 5) {
				var last = newContent;
				for (var i = 0; i < 5; i++)
					last = last.substr(last.indexOf(arr[i]) + arr[i].length);
				var top = newContent.substr(0, newContent.length - last.length);
				newContent = top.replace(reg, "<img src=$1>$3") + last;
			} else {
				newContent = newContent.replace(reg, "<img src=$1>$3");
			}
		}
		//newContent = newContent.replace(/(\r|\n|\r\n|\n\r)/gi, "<br>");
	}
	return newContent;
}

jQuery('#submit2').ready(function () {
	if (!jQuery("#jb_note").attr('id')) {
		//var jb_note = '<div id="jb_note"> <div class="jb_note_h"></div> <div class="jb_m"><h2></h2></div> <div class="jb_note_f"></div> </div>';
		var jb_note = '<div id="jb_note" style="display:none; position:absolute; width:500px; z-index:802">';
		jb_note += '<div style="background:url(http://static.tianyaui.com/js/bbs/image/notebg.png) no-repeat scroll 0 0 transparent; float:left; height:48px; width:1%;"></div>';
		jb_note += '<div style="background:url(http://static.tianyaui.com/js/bbs/image/notebg.png) repeat-x scroll 0 -54px transparent; color: #FFFFFF; float:left; height:48px; margin:0; text-align:center; width:98%">';
		jb_note += '<h2 style="font-size:16px; margin:0; padding:14px 20px 0;"></h2></div>';
		jb_note += '<div style="background:url(http://static.tianyaui.com/js/bbs/image/notebg.png) no-repeat scroll right 0 transparent; float: right; height: 48px; width:1%"></div> </div>';
		jQuery(document.body).append(jb_note);
	}
});
