var i = 0;
var t = 0;
var c = 0;
var ct = "web";

function _i(){i++;}

function vote(cat, score){	
	if(cat == 1)
		$("#art_rate_form .votes").fadeOut("slow", function(){
			postVote(cat, score);
			
		});
	else if(cat == 2)
		$("#storyline_rate_form .votes").fadeOut("slow", function(){
			postVote(cat, score);
		});
		
	
}

function postVote(cat, score){	
	$.ajax({"type": "POST", 
		"url": "/vote", 
		"data" : "c=" + c + "&i=" + i + "&t=" + t + "&cat=" + cat + "&s=" + score + "&ct=" + ct, 
		"success": function(data){handleVoteResponse(cat, data);}, 
		"error" : "showError",
		"dataType" : "xml"
	});
}

function handleVoteResponse(cat, xml){
	var msgType = $(xml).find("messageType").text();
	var msg = $(xml).find("message").text();
	var numVotes = $(xml).find("numVotes").text();
		
	if(cat == 1 && msgType != "0"){			
		$("#art_rate_form .votes").text("(" + numVotes + " votes)");
		$("#art_rate_form .votes").fadeIn("slow");
	}else if(cat == 2 && msgType != "0"){
		$("#storyline_rate_form .votes").text("(" + numVotes + " votes)");
		$("#storyline_rate_form .votes").fadeIn("slow");
	}else{
		alert(msg);
		if(cat == 1)
			$("#art_rate_form .votes").fadeIn("slow");
		else if(cat == 2)
			$("#storyline_rate_form .votes").fadeIn("slow");
	}
}

function showError(){
	alert("Oops, something went wrong and we were unable to register your vote. Please try again in a few minutes");
}

$(document).ready(function(){
	$("#art_rate_form .star-rating a").each(function(){
		$(this).click(function(){vote(1, $(this).attr("title"));});
	});		
	
	$("#storyline_rate_form .star-rating a").each(function(){
		$(this).click(function(){vote(2, $(this).attr("title"));});
	});
	
	$(".rating-cancel").remove();
});