/*
 * Poll anti-spam submit via AJAX
 * Based on: Ajax and PHP: Building Responsive Web Applications
 * Christian Darie, Bogdan Brinzarea, Filip Chereches, Mihai Bucica 
 */

var pollDiv;
var pollXmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
																		"MSXML2.XMLHTTP.5.0",
																		"MSXML2.XMLHTTP.4.0",
																		"MSXML2.XMLHTTP.3.0",
																		"MSXML2.XMLHTTP",
																		"Microsoft.XMLHTTP");
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
			try { 
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} catch (e) {
			}
		}
	}
	if (!xmlHttp)
		alert("Error creating the XMLHttpRequest object.");
	else 
		return xmlHttp;
}

function SubmitPoll(a,PollId,Script) {
	var PollSubmit = "&"+"Poll"+"Submit";
	a.href = a.href+PollSubmit;
	pollDiv = PollId;
	Script += PollSubmit;

	if (pollXmlHttp) {
		// try to connect to the server
		// open the script to handle voting if successful
		try {
			pollXmlHttp.open("GET", Script, true);
			pollXmlHttp.onreadystatechange = pollHandleRequestStateChange;
			pollXmlHttp.send(null);
		} catch (e) {
			alert("Can't connect to server: " + Script + "\n" + e.toString());
		}
		return true;
	}
}

function pollHandleRequestStateChange() {
	if (pollXmlHttp.readyState == 4) {
		if (pollXmlHttp.status == 200) {
			try {
				pollHandleServerResponse();
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem retrieving the data:\n" + pollXmlHttp.statusText);
		}
	} 
}

function pollHandleServerResponse() {
	// vote in the poll
	var Div = document.getElementById("PollView["+pollDiv+"]");
	response = pollXmlHttp.responseText;
	Div.innerHTML = response;
}
