/**
 * This file controls the user feedback stars system.
 * 
 * @author georgechild
 */

var xmlhttp;

function stars(v, o) {
	return ((typeof(o) == 'object' ? o : document).getElementById(v));
}

function $S(o) {
	return ((typeof(o) == 'object' ? o : stars(o)).style);
}

function agent(v) {
	return (Math.max(navigator.userAgent.toLowerCase().indexOf(v), 0));
}

function abPos(o) {
	var o = (typeof(o) == 'object' ? o : stars(o)), z = {X:0, Y:0};
	while(o != null)
	{
		z.X += o.offsetLeft;
		z.Y += o.offsetTop;
		o = o.offsetParent;
	};
	
	return (z);
}

function XY(e, v) {
	var o = agent('msie') ? {'X' : event.clientX + document.body.scrollLeft, 'Y' : event.clientY + document.body.scrollTop} : {'X' : e.pageX, 'Y' : e.pageY};
	return (v ? o[v] : o);
}

function stateChanged() {
	if (xmlhttp.readyState == 4) {
		var n = star.num;
		document.getElementById('starThanks' + n).innerHTML = xmlhttp.responseText;
	}
}

function GetStarsXmlHttpObject() {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	
	if (window.ActiveXObject) {
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	return null;
}

star = {};

star.mouse = function (e, o) {
	if (star.stop || isNaN(star.stop)) {
		star.stop = 0;

		document.onmousemove = function(e)
		{
			var n = star.num;
			var p = abPos(stars('star' + n)), x = XY(e), oX = x.X-p.X, oY = x.Y-p.Y;
			star.num = o.id.substr(4);

			if (oX < 1 || oX > 150 || oY < 0 || oY > 30) {
				star.stop = 1;
				star.revert();
			}
			else {
				$S('starCur' + n).width = Math.ceil(oX / 15) * 15 + 'px';
				$S('starUser' + n).color = '#888';
				stars('starUser' + n).innerHTML = Math.ceil(Math.round(oX / 150 * 100) / 10) * 10 + '%';
			}
		};
	}
};

star.update = function (e, o, userId) {
	var n = star.num, v = parseInt(stars('starUser' + n).innerHTML);

	n = o.id.substr(4);
	stars('starCur' + n).title = v;
	
	xmlhttp = new GetStarsXmlHttpObject();
	
	if (xmlhttp == null) {
		alert ("Your browser does not support HTTP Request. We cannot register your vote. Thank you anyway.");
		return;
	}
	
	var url = "feedback_process.php";
	url = url + "?vote=" + (v / 100);
	url = url + "&userid=" + userId;
	url = url + "&sid=" + Math.random();
	
	xmlhttp.onreadystatechange = stateChanged;
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
	
	document.onmousemove = '';
};

star.revert = function () {
	var n = star.num, v = parseInt(stars('starCur' + n).title);

	$S('starCur' + n).width = 0 + 'px';
	stars('starUser' + n).innerHTML = (v > 0 ? Math.round(v) + '%' : '');
	stars('starUser' + n).style.color = '#888';
	
	document.onmousemove = '';
};

star.num = 0;
