$(document).ready(function() {
	var itemId = $("input[name='vote-id']").val();
	var oldvalue = $("input[name='vote-old-value']").val();
	var contextPath = $("input[name='contextPath']").val();
	var votefor = $("input[name='votefor']").val();
	if (hasVoted(itemId, votefor)) {
		changeDivToImg(oldvalue);
	} else {
		$("div[id$='vote-box']").stars({
			cancelShow: false
			, select: oldvalue
			, callback: function(ui, type, value){
				votecounter(votefor, value, itemId, contextPath);
		    }
		});
	}
});

function hasVoted(itemId, votefor) {
	var cookie = $.cookie(getCookieName(itemId, votefor));
	var voted = !(cookie == null || cookie == "");
	return voted;
}

function getCookieName(itemId, votefor) {
	return "vote_" + votefor + "_" +itemId;
}

function changeDivToImg(value) {
	var contextPath = $("input[name='contextPath']").val();
	$("div[id$='vote-box']").html("<img src=\""+contextPath+"/themes/Reference/images/big_star_"+value+".gif\"/>");
}

function votecounter(voteforvalue, votevalue, idvalue, contextPath) {
	 $.cookie(getCookieName(idvalue, voteforvalue), votevalue, { expires: 180 });
	 $.ajax({
	      url: contextPath+'/votecounter'
	      ,type: 'get'
	      ,data: {votefor:voteforvalue, id:idvalue, value:votevalue}
	      ,datatype: 'html'
	      ,success: function(data, textStatus, XMLHttpRequest) {
	    	  changeDivToImg(votevalue);
	      }
	      ,error: function() {
	    	  backtooldvalue(); 
	      }
	 });
}

function backtooldvalue() {
	var oldvalue = $("input[name='vote-old-value']").val();
	$("div[name$='vote-box']").stars("select", oldvalue);
}
