// ==UserScript==
// @name           RForumQuickDeleter
// @namespace      http://linuxfire.com.cn/~moo/
// @author         mOo <mOo@linuxfire.com.cn>
// @include        http://forum.lighttpd.net/forum/*
// @description
// ==/UserScript==

(function(){
	function asyncRequest(method, url, values, onload, onerror)
	{
		var xmlHttpReq = false;
		// Mozilla/Safari
		if (window.XMLHttpRequest) {
			xmlHttpReq = new XMLHttpRequest();
		}
		// IE
		else if (window.ActiveXObject) {
			xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}

		try {
			xmlHttpReq.open(method, url, true);
		}
		catch(e) {
			document.title = e;
		}
		xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlHttpReq.onreadystatechange = function() {
			if (xmlHttpReq.readyState == 4) {
				onload(xmlHttpReq.responseText);
			}
		}
		if (onerror) {
			xmlHttpReq.onerror = onerror;
		}
		xmlHttpReq.send(values);
	}

	// find table.topics
	var tables = document.getElementsByTagName("TABLE");
	var table;
	for (var i = tables.length - 1; i >= 0; i--) {
		if (tables[i].className.indexOf("topics") != -1) {
			table = tables[i];
			break;
		}
	}
	if (!table) {
		return;
	}
	var rows = table.rows, l = rows.length;
	var tr, td, i, link;
	for (i = 0; i < l; i ++) {
		tr = rows[i];
		if (!tr.cells[0]) {
			continue;
		}
		td = tr.cells[0];
		if (td.nodeName != 'TD') {
			continue;
		}
		link = td.getElementsByTagName("A")[0];
		if (!link) {
			continue;
		}
		(function(tr) {
			var checkbox = document.createElement('input');
			checkbox.type = "checkbox";
			checkbox.value = link.href.replace(/.*?\/topic\/(\d+).*/, "$1");
			checkbox.checked = tr.className.indexOf('deleted-topic') != -1;
			checkbox.onclick = function() {
				var act = checkbox.checked ? "delete_post" : "undelete_post";
				var onerror = function() {
					checkbox.disabled = false;
					checkbox.checked = !checkbox.checked;
				}
				var operatePost = function() {
					asyncRequest("GET", "../topic/" + act + "/" + checkbox.firstpostid, null, function(content) {
						checkbox.disabled = false;
						tr.className = tr.className.replace(/\bnew-posts\b/g, "");
						if (checkbox.checked) {
							tr.className += " deleted-topic";
						}
						else {
							tr.className = tr.className.replace(/\bdeleted-topic\b/g, "");
						}
					}, onerror);
				}

				this.disabled = true;
				if (!this.firstpostid) {
					checkbox.title = "loading first postid";
					asyncRequest("GET", "../topic/" + checkbox.value, null, function(content) {
						if (/\/topic\/(un)?delete_post\/(\d+)/.test(content)) {
							checkbox.firstpostid = RegExp.$2;
							operatePost();
						}
						else {
							onerror();
						}
					}, onerror);
				}
				else {
					operatePost();
				}
			}
			td.firstChild ? td.insertBefore(checkbox, td.firstChild) : td.appendChild(checkbox);
		})(tr);
	}
})();

