var xmlReq = null;
var anecId = 0;

function rate(id) {
	var rank = document.getElementById("rank_" + id).value;
	if (rank < 0 || rank > 9) {
		alert('Blje!');
		return;
	}

	if (xmlReq == null) {
		xmlReq = initXMLReq();
	}

	if (xmlReq == null) {
		alert('Tavs browseris ir pārāk labs šādām izvirtībām,\ntāpēc tev balsošana pašlaik nav pieejama.');
		return;
	}

	if (anecId > 0) {
		alert('Iepriekšējais vērtējums vēl nav apstrādāts.');
		return;
	}

	anecId = id;// nested functions

	xmlReq.open("GET", "vote.php?anecid=" + id + "&rank=" + rank, true);
	try {
		xmlReq.addEventListener("readystayechange", onReadyStateChange, false);// GECKO
	} catch (e) {
		xmlReq.onreadystatechange = onReadyStateChange;// IE
	}

	xmlReq.send("");
}

onReadyStateChange = function(ev) {
	switch (xmlReq.readyState) {
		case 1:
		case 2:
		case 3:
			initProgressMessage();
			return;
		case 4:
			initVoteResult();
			return;
	}
}

function initProgressMessage() {
	var container = document.getElementById("rating_" + anecId);
	switch (xmlReq.readyState) {
		case 1:
			container.innerHTML = "Konektējamies..";
			break;
		case 2:
			container.innerHTML = "Gaidam datus..";
			break;
		case 3:
			container.innerHTML = "Lādējam datus..";
			break;
	}
}

function initVoteResult() {
	if (xmlReq.status != 200) {
		document.getElementById("rating_" + anecId).innerHTML = xmlReq.status + ": " + xmlReq.statusText;
	} else {// ok, xml loaded
		var container = document.getElementById("rating_" + anecId);
		container.innerHTML = "";

		var xmlDoc = xmlReq.responseXML;
		if (xmlDoc == null) {
			container.innerHTML = "Hmm, slikti gan.. :(";
		} else {
			var root = xmlDoc.documentElement;
			if (root.firstChild.nodeName == "error") {
				container.innerHTML = root.firstChild.firstChild.nodeValue;
			} else {
				var count;
				var average;
				for (i = 0; i<root.childNodes.length; i++) {
					if (root.childNodes[i].nodeName == "count") {
						count = root.childNodes[i].firstChild.nodeValue;
					} else if (root.childNodes[i].nodeName == "average") {
						average = root.childNodes[i].firstChild.nodeValue;
					}
				}
				container.innerHTML = '<div class="rate">Vērtējums: ' + average + ' (balsojuši: ' + count + ')</div>';
			}
		}
	}
	anecId = 0;
}


function initXMLReq() {
	if (typeof XMLHttpRequest != 'undefined') {
		xmlReq = new XMLHttpRequest();
	} else if (typeof ActiveXObject != 'undefined') {
		xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		return null;
	}

	return xmlReq;
}
