/*
 * copy from http://pinglun.qq.com/js/comment_lib.js
 * modified by hobo at 2007-4-30
 */

try
{
	document.domain = "qq.com";
}
catch (e)
{
}

window.debug = false;

var Comment = new Object();

Comment.Configure = {
	version: "1.1",
	author: "colin&hobo",
	newline: "\n",
	statusBar: true,
	default_reply_per_page: 30,
	index_line_sum: 10000,
	index_domain: "http://comment3.qq.com/"
};

Comment.ContentFormat = {
	decode: function(content)
	{
		return content.split(Comment.Configure.newline);
	},

	faceEncode: function(content)
	{
		return content.replace(/\[a(\d)\]/ig, "<img src='images/face/$1.gif'/>");
	}
};

Comment.UrlFactory = {
	commentUrlFormatStr: Comment.Configure.index_domain + "{0}/normal/{1}/{2}.htm{3}",
	replyUrlFormatStr: Comment.Configure.index_domain + "{0}/normal/{1}/reply/{2}.htm{3}",

	getCacheString: function(cache)
	{
		return cache ? "?cache="+Math.random() : "";
	},

	getCommentDir: function(id)
	{
		var path = parseInt(id / 1000000) + '/';
		path += parseInt(id / 1000) + '/';
		path += id / 1;
		return path;
	},

	getCommentSumUrl: function(site, id, nocache)
	{
		return String.format(this.commentUrlFormatStr,
			site, this.getCommentDir(id), "sum", this.getCacheString(nocache));
	},

	getCommentInfoUrl: function(site, id, nocache)
	{
		return String.format(this.commentUrlFormatStr,
			site, this.getCommentDir(id), "commentinfo", this.getCacheString(nocache));
	},


	getCommentOriginIndexUrl: function(site, id, sum, nocache)
	{
		return String.format(this.commentUrlFormatStr,
			site,
			this.getCommentDir(id),
			"originindex/0000" + Math.floor(sum/Comment.Configure.index_line_sum),
			this.getCacheString(nocache));
	},

	getReplyDir: function(key)
	{
		try
		{
			var path = key.substr(0, 8);
			path += '/' + (key.substr(8, 4));
			path += '/' + (key.substr(12, 2));
			path += '/' + key;
			return path;
		}
		catch (e)
		{
			return null;
		}
	},

	getReplyInfoUrl: function(site, id, key, nocache)
	{
		return String.format(this.replyUrlFormatStr,
			site, this.getCommentDir(id), this.getReplyDir(key), this.getCacheString(nocache));
	}
};

Comment.DataObjectFactory = function(content, model)
{
	content = Comment.ContentFormat.decode(content);
	var dataModel = Comment.DataObject[model];
	var dataObject = {};

	for (var i=0; i<dataModel.length; i++)
	{
		dataObject[dataModel[i]] = content[i];
	}

	return dataObject;
};

Comment.DataObject = {
	'commentinfo': [
		'site_cn',
		'sort_en',
		'sort_cn',
		'source',
		'source_url',
		'title',
		'url',
		'intro',
		'intro_img',
		'group_id',
		'intro_show',
		'create_time',
		'debate_id'
	],
	"sum": [
		"origin_count",
		"total_count",
		"top_count"
	],
	'reply': [
		'comment_id',
		'uin',
		'nickname',
		'pub_time',
		'pass_time',
		'ip',
		'title',
		'content',
		'reply_key',
		'is_del',
		'reply_type',
		'reply_kind',
		'tips',
		'sums'
	]
};

Comment.PGV = function()
{
	if (typeof pgvMain == "function")
	{
		pvRepeatCount = 1;
		pgvMain();
	}
};

/*
 * Comment.QQ.Com Comment.Proxy Version 1.0 2007-4-30 <hobowo#tencent.com>
 */

Array.prototype.removeAt = function(i)
{
	this.splice(i, 1);
};

Array.prototype.remove = function(o)
{
	var i = this.indexOf(o);
	
	if (i != -1)
	{
		this.splice(i, 1);
	}
};

Comment.StatusBar = {
	show: function(s, b)
	{
		if (Comment.Configure.statusBar)
		{
			if (!$("loading"))
			{
				divLoading = $C('div');
				divLoading.id = 'loading';
				divLoading.style.position = "absolute";
				divLoading.style.backgroundColor = "#FF4447";
				divLoading.style.display = "none";
				divLoading.style.padding = "3px 5px";
				divLoading.style.color = "#FFF";
				document.getElementsByTagName('body')[0].appendChild(divLoading);
			}

			$("loading").innerHTML = (s!=null && b) ? s : "数据加载中...";
			$("loading").style.top = (document.documentElement.scrollTop || document.body.scrollTop) + "px";
			$("loading").style.left = (document.documentElement.scrollLeft || document.body.scrollLeft) + "px";
			$("loading").style.display = "block";
		}
	},

	hide: function()
	{
		try
		{
			$("loading").style.display = "none";
		}
		catch (e)
		{
		}
	}
};

Comment.Proxy = {
	callbackFactory: function(callback, dataObject, key)
	{
		return {
			onSuccess: function(xmlHttp)
			{
				if (dataObject != null)
				{
					if (typeof key != "undefined")
					{
						callback(Comment.DataObjectFactory(xmlHttp.responseText, dataObject));
					}
					else
					{
						callback(Comment.DataObjectFactory(xmlHttp.responseText, dataObject));
					}
				}
				else
				{
					callback(Comment.ContentFormat.decode(xmlHttp.responseText));
				}
			},
			onFailure: function()
			{
				callback(null);
			}
		};
	},

	getCommentSum: function(site, id, callback)
	{
		var commentSumUrl = Comment.UrlFactory.getCommentSumUrl(site, id, true);
		ProxyLoader.load(commentSumUrl, this.callbackFactory(callback, "sum"));
	},

	getCommentInfo: function(site, id, callback)
	{
		var commentInfoUrl = Comment.UrlFactory.getCommentInfoUrl(site, id, true);
		ProxyLoader.load(commentSumUrl, this.callbackFactory(callback, "commentinfo"));
	},

	getCommentOriginIndex: function(site, id, sum, callback)
	{
		var commentOriginIndexUrl = Comment.UrlFactory.getCommentOriginIndexUrl(site, id, sum, true);
		ProxyLoader.load(commentOriginIndexUrl, this.callbackFactory(callback));
	},

	getReplyInfo: function(site, id, key, callback)
	{
		var replyInfoUrl = Comment.UrlFactory.getReplyInfoUrl(site, id, key, true);
		ProxyLoader.load(replyInfoUrl, this.callbackFactory(callback, "reply", key));
	},

	printCommentSum: function(site, id, container)
	{
		var commentSumUrl = Comment.UrlFactory.getCommentSumUrl(site, id, true);
		ProxyLoader.load(commentSumUrl, {
			onSuccess: function(xmlHttp)
			{
				$(container).innerHTML = Comment.DataObjectFactory(xmlHttp.responseText, 'sum')['total_count'];
			},
			onFailure: function()
			{
				$(container).innerHTML = 0;
			}
		});
	}
};

var retry = false;

Comment.Proxy.Page = {
	load: function(site, id, reload)
	{
		if (!reload)
		{
			this._site = site;
			this._id = id;
		}

		this.init();
		Comment.Post.init(site, id)
	},

	init: function()
	{
		this._replyPerPage = Comment.Configure.default_reply_per_page;
		this._currPage = 1;
		this._totalPage = 1;
		this._commentOriginIndex = [];
		this._replys = {};

		this.bindPageInfo();
	},

	bindPageInfo: function()
	{
		var _this = this;

		Comment.StatusBar.show("评论总数加载中...");
		Comment.Proxy.getCommentSum(this._site, this._id, function(commentSum)
		{
			if (commentSum)
			{
				Comment.StatusBar.hide();
				//$("Comment_Sum").innerHTML = commentSum["total_count"];
				_this._totalReply = parseInt(commentSum["origin_count"]);
				_this.bindReplyList();
			}
			else
			{
				Comment.StatusBar.show("评论总数加载失败");
			}
		});
	},

	bindReplyList: function()
	{
		var _this = this;

		Comment.StatusBar.show("评论索引加载中...");
		Comment.Proxy.getCommentOriginIndex(this._site, this._id,
			(_this._totalReply - Comment.Configure.default_reply_per_page*(this._currPage-1)),
			function(commentOriginIndex)
		{
			if (commentOriginIndex)
			{
				Comment.StatusBar.hide();
				commentOriginIndex.pop();

				var m = Math.floor(_this._totalReply/Comment.Configure.index_line_sum);
				var n = Math.floor((_this._totalReply
									- Comment.Configure.default_reply_per_page*(_this._currPage-1))
										/Comment.Configure.index_line_sum);
				var f = _this._totalReply % Comment.Configure.index_line_sum;
				//var l = commentOriginIndex.length;


				if (m != n)
				{
					var a = new Array(f+(m-n-1)*Comment.Configure.index_line_sum);
				}
				else
				{
					var a = new Array(0);
				}

				_this._commentOriginIndex = a.concat(commentOriginIndex.sortByAlpha());

				_this.createPage(_this._currPage);
			}
			else
			{
				Comment.StatusBar.show("评论索引加载失败");
			}
		});
	},

	bindReplys: function()
	{
		var _this = this;

		var startPage = (this._currPage-1) * this._replyPerPage;
		if (this._currPage == this._totalPage)
		{
			var endPage = this._totalReply - 1;
		}
		else
		{
			var endPage = this._currPage * this._replyPerPage - 1;
		}
		var replyCount = endPage - startPage + 1;
		var currPage = this._currPage;

		if (typeof this._commentOriginIndex[endPage] == "undefined")
		{
			this.bindReplyList();
			return;
		}

		Comment.StatusBar.show("评论加载中...");

		for (var i=startPage; i<=endPage; i++)
		{
			Comment.Proxy.getReplyInfo(this._site, this._id, this._commentOriginIndex[i], 
				bindCommentOriginIndexFactroy(currPage, this._commentOriginIndex[i], replyCount, i-startPage, i));
		}

		function bindCommentOriginIndexFactroy(currPage, commentOriginIndex, replyCount, index, i)
		{
			return function(replyInfo)
			{
				bindReplys(currPage, commentOriginIndex, replyInfo, replyCount, index, i);
			};
		}

		function bindReplys(currPage, key, replyInfo, replyCount, index, i)
		{
			_this._replys[currPage] = _this._replys[currPage] || {reply: []};
			if (replyInfo)
			{
				replyInfo["key"] = key;
				//replyInfo["content"] = Comment.ContentFormat.faceEncode(replyInfo["content"]);
			}

			//if (true || !replyInfo || (replyInfo["is_del"] == "2") || !replyInfo["content"])
			//{
			//	retry = true;
			//	_this._commentOriginIndex.removeAt(i);
			//	_this._replys[currPage].reply[index] = null;
			//}
			//else
			//{
				//_this._replys[currPage].reply[index] = replyInfo;
				_this._replys[currPage].reply.push(replyInfo);
			//}

			if (replyCount == _this._replys[currPage].reply.length)
			{
				//if (retry)
				//{
				//	_this._replys[currPage] = null;
				//	_this.createPage(currPage);
				//}
				//else
				//{
					Comment.StatusBar.hide();
					var page = {
						totalReply: _this._totalReply,
						currPage: _this._currPage,
						currPages: replyCount,
						totalPage: _this._totalPage
					};

					$("Page_Nav").innerHTML = TrimPath.processDOMTemplate("Page_Nav_View", page);
					$("Content").innerHTML = TrimPath.processDOMTemplate("Content_View", _this._replys[currPage]);
					Comment.PGV();
				//}
			}
		}
	},

	bindPageNav: function()
	{
		//this._totalReply = this._commentOriginIndex.length;
		this._totalPage = Math.ceil(this._totalReply / this._replyPerPage);
	},

	createPage: function(n)
	{
		retry = false;
		this._currPage = n;
		this._replys[n] = null;

		this.bindPageNav();
		if (n>this._totalPage)
		{
			return;
		}
		this.bindReplys();
	}
};

Comment.Post = {
	_site: null,
	_id: null,
	init: function(site, id)
	{
		Comment.Post._site = site;
		Comment.Post._id = id;
		$("c_site").value = site;
		$("c_id").value = id;
	},

	checkForm: function(form)
	{
		if (form.a.value.trim() == "")
		{
			alert("很抱歉，请输入推荐人");
			form.a.focus();
			return false;
		}
		if (form.b.value.trim() == "")
		{
			alert("很抱歉，请输入词条名称");
			form.b.focus();
			return false;
		}
		if (form.c.value.trim() == "")
		{
			alert("很抱歉，请输入推荐理由");
			form.c.focus();
			return false;
		}
		if (form.c.value.trim().length > 300)
		{
			alert("很抱歉，推荐理由字数请控制在300字以内");
			form.c.focus();
			return false;
		}

		form.c_content.value = form.a.value.trim() + "\x0f" +
			form.b.value.trim() + "\x0f" + form.c.value.trim();

		form.action = "http://input.comment.qq.com/post.cmt";
		Comment.StatusBar.show("正在发送...");
		form.a.value = "";
		form.b.value = "";
		form.c.value = "";
		$("c_site").value = Comment.Post._site;
		$("c_id").value = Comment.Post._id;
		return true;
	},

	callback: function(url)
	{
		$('post_async').src = 'about:blank';
		Comment.StatusBar.hide();
		this.doAlert(parseInt(new UrlParser(url).getParam("code")));
	},

	doAlert: function(code)
	{
		var errMsg = '';

		switch (code)
		{
			case -1:
				errMsg = '您的评论已提交审核，感谢您的参与';
				break;
			case 0:
				errMsg = '提交成功，感谢您的参与';
				window.location.reload();
				//window.setTimeout(Comment.Proxy.Page.load.bind(Comment.Proxy.Page, null, null, true), 300);
				break;
			case 1:
				errMsg = '很抱歉，您填写的内容不完整，请重新输入您的内容';
				break;
			case 2:
				errMsg = '很抱歉，您尚未登录或登录已经过期，请先登录';
				break;
			case 3:
				errMsg = '您的评论已提交审核，感谢您的参与';
				break;
			case 4:
				errMsg = '您的IP地址已暂时被屏蔽';
				break;
			case 5:
				errMsg = '您的QQ号已暂时禁止在本评论系统发言';
				break;
			case 6:
				errMsg = '很抱歉，您的QQ号码和密码不匹配';
				break;
			case 7:
				errMsg = '很抱歉，系统繁忙，请稍候再试';
				break;
			case 8:
				errMsg = '很抱歉，您的操作频率太快，请稍后再试';
				break;
			case 9:
				errMsg = '很抱歉，您的验证码输入错误';
				break;
			case 10:
				try
				{
					Tips.Up.done();
				}
				catch (e)
				{
				}
				//errMsg = '很抱歉，您的验证码输入错误';
				break;
		}

		if (errMsg != '')
		{
			alert(errMsg);
		}
	}
};