var type = "survey";

function XHRFactory()
{
	if(window.XMLHttpRequest)
	{
		return new XMLHttpRequest();
	}

	else if(window.ActiveXObject)
	{
		return new ActiveXObject("Microsoft.XMLHTTP");
	}

	throw("XMLHTTPRequest not supported");
}

function SwitchStars(on, stars, start)
{
	for(var i = start-1; i >= 0; i--)
	{	
		onoff = stars.item(i).getAttribute("alt").substr(2);
		
		if(on)
		{
			var src = "./images/star-hover.png";
		}
		
		else
		{
			var src = "./images/star-"+onoff+".png";
		}
		
		stars.item(i).setAttribute("src", src);
	}
}

function ChangeStarText(text)
{
	var stardiv = document.getElementById("stars");
	
	while(stardiv.childNodes.length > 0)
	{
		stardiv.removeChild(stardiv.firstChild);
	}
	
	var node = document.createTextNode(text);
	
	stardiv.appendChild(node);
}

function Vote(id, rating)
{
	try
	{
		var xhr = XHRFactory();
	}
	
	catch(e)
	{
		return;
	}
	
	ChangeStarText("Casting...");
	
	xhr.open("get", path+"/vote_q.php?id="+id+"&rating="+rating+"&type="+type);
	
	xhr.onreadystatechange = function()
	{
		if(xhr.readyState == 4)
		{
			ChangeStarText(xhr.responseText);
		}
	}
	
	xhr.send(null);
}

function SetStarEvents()
{
	var stars = document.getElementById("stars").getElementsByTagName("img");
	
	for(var i = 0; i < stars.length; i++)
	{
		stars.item(i).onmouseover = function()
		{
			SwitchStars(true, stars, this.getAttribute("alt").substr(0, 1));
		}
		
		stars.item(i).onmouseout = function()
		{
			SwitchStars(false, stars, this.getAttribute("alt").substr(0, 1));
		}
		
		stars.item(i).onclick = function()
		{
			Vote(document.getElementById("id").getAttribute("value"), this.getAttribute("alt").substr(0, 1));
		}
	}
}

SetStarEvents();