var currentPos = new Array();
var currentAvg = new Array();
var contentTypeKey = new Array();
var posted = new Array();

$(document).ready(function() {
	$(".pnlAltRatingActive").mousemove(function(e) {
		id = $(".pnlAltRatingLit", this).attr("class").substring(21);

		if(posted[id] == undefined || posted[id] == 0) {
			imgOffset = $(this).offset();
			x = Math.ceil((e.pageX - imgOffset.left) / ($(this).width() / 5));
			setImagePos( id, x );
		}
	});

	$(".pnlAltRatingActive").mouseleave(function(e) {
		id = $(".pnlAltRatingLit", this).attr("class").substring(21);

		setImagePos( id, currentAvg[id] );
	});


	$(".pnlAltRatingActive").click(function(e) {
		id = $(".pnlAltRatingLit", this).attr("class").substring(21);
		
		if((posted[id] == undefined || posted[id] == 0) && currentPos[id] != undefined) {
			$.post( "/ratings/7/" + contentTypeKey[id] + "/" + id, { 'ratingvalue': Math.round(currentPos[id]) }, function(xml) {

				if($("result", xml).attr("save") == "ok") {
					posted[id] = 1;
					currentAvg[id] = $("average", xml).text();
					setImagePos( id, currentAvg[id] );
//					currentAvg[id] = Math.round(currentPos[id]);
					$("#count_" + id).html($("count", xml).text());
					$("#helptext_" + id).text("Takk for din stemme.");

					//GA Tracking
					_gaq.push(['_trackEvent', 'Rating', 'Ga stemme', title + " (" + id + ")", Math.round(currentPos[id])]);
				} else {
					$("#helptext_" + id).addClass("red").text("Du har allerede stemt.");

					//GA Tracking
					_gaq.push(['_trackEvent', 'Rating ', 'Allerede stemt']);
				}
			});
		} else {
			$("#helptext_" + id).addClass("red").text("Du har allerede stemt.");
			_gaq.push(['_trackEvent', 'Rating ', 'Allerede stemt']);
		}
	});

});

function getCurrentAverage(id) {
	$.get("/ratings/7/" + id, { r: Math.random() }, function(xml) {
		id = parseInt($("contentkey", xml).text());
		currentAvg[id] = $("average", xml).text();
		$("#count_" + id).html($("count", xml).text());
		setImagePos( id, currentAvg[id] );
	});
}

function setImagePos( id, x ) {
	if(currentPos[id] == undefined || currentPos[id] != x) {
		$(".rate_" + id).css({ width: (x / 5 * 100) + "%" });
		//$(".rate_" + id).css({ backgroundPosition: Math.ceil(-121 + (x * 20)) + "px 0px" });
		currentPos[id] = x;
	}
}
