//TODO, move this somewhere more generic, its a nice func :)
if(typeof(addOnloadEvent) != 'function'){
	function addOnloadEvent(fnc){
		if (typeof window.addEventListener != "undefined") {
			window.addEventListener("load", fnc, false);
		}else if (typeof window.attachEvent != "undefined") {
			window.attachEvent("onload", fnc);
		} else {
			if ( window.onload != null ) {
				var oldOnload = window.onload;
				window.onload = function (e) {
					oldOnload(e);
					window[fnc]();
				};
			} else {
				window.onload = fnc;
			}
		}
	}
}

function addAjaxRatings(groupid, contentid) {
	//lets try find the links for voting, and ajax-ify them :)
	var link;
	for(var i=0; i<=100; i++) {
		//we have a link with out group and content, as well as a rating. sweet 
		if(link = document.getElementById("wc-rating-"+groupid+"-"+contentid+"-"+i)) {
			link.onclick = function() {
				rateContentItem(this.id);
				return false; //stop normal click
			}
		}
	}
}

function rateContentItem(groupid, contentid, rating) {
	if(groupid && !contentid && !rating) { //then 'groupid' has been passed like this: wc-rating-[groupid]-[contentid]-[rating]
		var split = groupid.split("-"); //so split out the values we need
		groupid = split[2];
		contentid = split[3];
		rating = split[4];
	}
	
	if (window.XMLHttpRequest) {
		var req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		var req = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	var url;
	url = "/ratings.php?action=ajaxRateContent&groupid="+groupid+"&contentid="+contentid+"&rating="+rating;
	req.open('GET', url, true);
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var html = req.responseText;
			if(html.substr(0, 11) == "ERROR_CODE:") {
				var code = html.substr(11, 4);
				var msg = html.substr(16);
				
				var errBox;
				if(errBox = document.getElementById("rating-alert-"+groupid+"-"+contentid)) {//if div exists, show inline error
					errBox.innerHTML = msg;
					errBox.style.display = "";
				}else{ //or go with crappy alert
					alert(msg);
				}
			}else{
				document.getElementById("wc-rating-container-"+groupid+"-"+contentid).innerHTML = html;
			}

			
		}
	}
	req.send(null);				
	return false;
}