var cur_req;
var cur_req_cb;

function async_request(url, cb) {
	var req;

	if(cur_req) {
		cb({"result": "fail", "message": "Request in progress"});
		return;
	}

	if(window.XMLHttpRequest)
		req=new XMLHttpRequest();

	else if(window.ActiveXObject)
		req = new ActiveXObject("Microsoft.XMLHTTP");

	else {
		cb({"result": "fail", "message": "Browser doesn't support AJAX"});
		return;
	}

	if(!req) {
		cb({"result": "fail", "message": "Bug"});
		return;
	}

	req.onreadystatechange = function() {
		if(cur_req.readyState != 4)
			return;
		
		var response = new Array();

		if(cur_req.status == 200) {
			lines = cur_req.responseText.split("\n");
			for(var l in lines) {
				l = lines[l].split("\r")[0];
				idx = l.indexOf("=");
				if(idx != -1) {
					key = l.substr(0, idx);
					val = l.substr(idx+1);
					response[key] = val;
				}
			}
		} else {
			response["result"] = "fail";
			response["message"] = "HTTP status " + cur_req.status;
		}

		if(response["result"] == null) {
			response["result"] = "fail";
			response["message"] = "Malformed reply";
		}
		
		cur_req_cb(response);
		cur_req = null;
	}

	cur_req = req;
	cur_req_cb = cb;

	req.open("POST", url, true);
	req.send(null);

	return req;
}

function cast_vote(id, vote_for) {
	url = "/submit/" + id + "/vote_aj/";
	if(vote_for) url += "for/";
	else url += "against/";

	function cb(response) {

		if(response["result"] == "fail") {
			alert(response["message"]);

			/* AJAX is teh phail, so fall back on the old
			 * way. Darn this new-fangled AJAX stuff. When
			 * I were a wee'un we used to do it like this,
			 * and it were uphill both ways... */

			url = "/submit/" + id + "/vote/";
			if(vote_for) url += "for/";
			else url += "against/";

			url += "?prev=" + encodeURIComponent(document.location.href);

			document.location.href = url;

		} else {		
			vf = document.getElementById("votes_for_" + id);
			vf.innerHTML = "(" + response["for"] + ")";

			va = document.getElementById("votes_against_" + id);
			va.innerHTML = "(" + response["against"] + ")";
		}
	}

	async_request(url, cb);
}

function show_comment_entry(index) {
	document.getElementById(index).style.display = "block";
}

function approve_submission(id) {
	var catsel = document.getElementById("category" + id);
	var catidx = catsel.selectedIndex;
	var catopt = catsel.options[catidx];
	
	document.location.href = "/moderate/" + id + "/approve/" + catopt.value + "?prev=" + encodeURIComponent(document.location.href);
}
