//use jQuery in compatibility mode
$j = jQuery.noConflict();

var checkboxTimer;
var voteType;

function initStars() {
	$j('form.stars input[type=radio]').each(function() {
		var rater = $j(this);
		voteType = $j(this).parents("form").find("input[name=voteType]").val();

		rater.hide();
		rater.rating({
			split: (rater.parents('form').hasClass('user-voted')) ? 2:1,
			readOnly:(rater.parents('form').hasClass('user-voted')||rater.parents('form').hasClass('read-only'))?true:false, // this will disable the stars
			required:true,
			starWidth: 16,
			useThumbs: (voteType == 3) ? true:false,
			callback: function(value, link)
			{
				//lockStars(value, link);
				var sportId = $j(this).parents("form").find("input[name=sportId]").val();
				var gameId = $j(this).parents("form").find("input[name=gameId]").val();

				startLoad(sportId, gameId);
				var req = "http://insider.espn.go.com/grail/rater/vote?sportId="+sportId+"&gameId="+gameId+"&voteType="+voteType+"&vote="+value;

				try {
					JSONscriptRequest(req);

					//over write or create cookie storing vote
					createCookie('gr_vote_'+sportId+'_'+gameId, value);
				} catch(e) {}

			}
		});

	});
	$j('form.stars input[type=submit]').hide(); // hide the form submit buttons
}


function handleVoteResult(sportId, gameId, data) {

	endLoad(sportId, gameId);

	if (data != -1) {
		$j("#user-rating-sport-"+sportId+"-game-"+gameId+"-form").siblings(".voteLoad").html('<img class="checkmark" src="http://assets.espn.go.com/grail/i/check.gif" />');
		checkboxTimer = setTimeout(removeSuccess, 5000);
	} else {
		$j("#user-rating-sport-"+sportId+"-game-"+gameId+"-form").siblings(".voteLoad").html('<b style="color:#f00;">Error</b>');
	}
}

function removeSuccess() {
	$j(".checkmark").remove();
}

function createCookie(name,value) {
	document.cookie = name+"="+value+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"");
}

/**
 * This function should really be factored into the rating code.
 * Preferrably, refactor the rating to be more like the slider control.
 */
function setRating( name, value ) {

	//Drop a cookie for this game
	var nameParts = name.split("-");
	if (nameParts.length == 6) {
		var gameId = nameParts[5];
		var sportId = nameParts[3];

		//try to find existing cookie
		gr_cookie = readCookie('gr_vote_'+sportId+'_'+gameId);
		if (gr_cookie == null) {
			createCookie('gr_vote_'+sportId+'_'+gameId, value);
		}
	}
	/* This is a major hack for timeliness.  I'm facking the call to the click event on the cell that has the value I'm interested in.  Because the event is faked, I have to pass the callback separately. */
	var settings = { useThumbs: (voteType && voteType == 3) ? true:false };
	var star = $j('#' + name + '-form').find(' div a[title=' + value + ']').parent()[0];
	$j.rating.event.click(name, star, settings);
}

/**
 * Due to a major hack on my part, this is a named function such that it can
 * be referenced easily.
 */
function lockStars(value,link) {
	// disable the star ratings once the user votes
	$j(link).parents('form').addClass('user-voted');
	/* Modified to not use $(this) so it will work from two contexts. */
	$j(link).parent().siblings('div.star').andSelf().removeClass('star_live').addClass('star_readonly').unbind();
	idea_id = $j(link).parents('form').find('input[name=idea]').val();
}

function startLoad(sportId, gameId) {
	clearTimeout(checkboxTimer);
	var voteLoad = $j("#user-rating-sport-"+sportId+"-game-"+gameId+"-form").siblings(".voteLoad");
	voteLoad.find(".loadImg").remove();
	voteLoad.find(".checkmark").remove();
	voteLoad.prepend('<img class="loadImg" src="http://assets.espn.go.com/grail/i/spin.gif" />');
}

function endLoad(sportId, gameId) {
	$j("#user-rating-sport-"+sportId+"-game-"+gameId+"-form").siblings(".voteLoad").find(".loadImg").remove();
}

function showGameRaterLogin() {
	$j(".usrLoad").remove();
	$j(".usrVote .voteLabel").html("Please <a href='https://r.espn.go.com/espn/memberservices/pc/login?appRedirect="+encodeURIComponent(document.location.href)+"'>login</a> to vote.");
	$j(".usrVote .voteLabel").show();
	$j("form.stars").remove();

}
/*
function enableStars(sportId, gameId) {
	$j(".usrLoad").remove();
	$j(".usrVote .voteLabel").show();
	$j("#user-rating-sport-"+sportId+"-game-"+gameId+"-form").show();
}
*/
function enableAllStars() {

	var voteDiv = $j("div.usrVote");

	for(var i=0;i<voteDiv.length;i++){
		$j('.usrLoad',$j(voteDiv[i])).remove();
		$j('.voteLabel',$j(voteDiv[i])).show();
	}

	$j('form.stars').show();
}

function getUserRatings(allgames) {
	var added = false;
	var query = "games=";
	var gr_cookie;
	var isLoggedIn = loggedIn();


	if (!isLoggedIn) {
			showGameRaterLogin();
	} else {
		enableAllStars();

		for(g=0; g<allgames.length; g++) {
			var gameObj = allgames[g];
			sport = gameObj.sportId;
			game = gameObj.gameId;

			var rater = $('#user-rating-sport-'+sport+'-game-'+game+'-form');
			if (rater.id == null || rater.id.length == 0) { return; }

			gr_cookie = readCookie('gr_vote_'+sport+"_"+game);

			if (gr_cookie != null) {
				//vote stored in a cookie
				setRating( "user-rating-sport-"+sport+"-game-"+game, gr_cookie);
			} else {
				if (added) { query += ","; }
				query += sport + "." + game;
				added = true;
			}
		}
	}

	query += "&voteType="+voteType;

	//try retrieving vote
	if (typeof window.blue != 'undefined') { query += '&amp;blue=' + escape(window.blue); }
	if (typeof window.green != 'undefined') { query += '&amp;green=' + escape(window.green); }

	if (added) {
		var req = 'http://insider.espn.go.com/grail/rater/userratings?' + query;
		JSONscriptRequest(req);
	}

}

function loggedIn() {
	return document.cookie.match(/SWID=\{[\d\w-]+\}/i) || false;
}

//Once the page loads, initialize the stars.
$j(initStars);