<!-- Move to external file! -->

var grail_prevVoteValue
/* ActivePopup simply holds all required items to destroy a popup and reset the buttons css. */
var activePopup = null;
function ActivePopup( button, dialogId, dialog ) {
	this.button = button;
	this.dialogId = dialogId;
	this.dialog = dialog;
}


/* Set a timer to run every 250 ms checking if the current hash indicates to close an active dialog. */

$.timer( 250, function( timer ) {
	if(activePopup != null) {
		if( activePopup.cancelTimer ) {
			timer.stop();
		} else {
			var shouldClose = location.hash;
			if( shouldClose.indexOf("closeDialog") > -1) {
				closeVoteDialog( activePopup.dialogId );
				activePopup = null;
				location.hash = "leaveOpen";
			}
		}
	}
} );


/**
 *  Displays a popup dialog for voting, ensuring that only one is open at a time.
 *  Currently, relies on a page scoped variable.
 */
function showVoteDialog( dialogId, buttonElement, sport, game, voteType ) {
	var showPopup = false

	if (activePopup != null && activePopup.dialogId != dialogId)
	{
		showPopup = true
	}
	else if (activePopup == null)
	{
		showPopup = true
	}

	if( activePopup != null ) {
		closeVoteDialog( activePopup.dialogId );
	}

	if (showPopup == true)
	{
		var button = $(buttonElement)
		/* First, check if dialog was already created. */
		var dialog = $("#"+dialogId);
		if( dialog.length == 0 ) { /* Create dialog. */
			var newDialog = $("<iframe id='" + dialogId + "' class='flora' allowtransparency='true' src='http://insider.espn.go.com/grail/inline/votepopup?dialogId=" + dialogId + "&amp;sportId=" + sport + "&amp;gameId=" + game + "&amp;voteType=" + voteType + "&amp;puri="+escape(location.href)+"' height='159px' width='329px' scrolling='no' frameborder='0' ></iframe>");
			$("body").append(newDialog);
			var offset = button.offset();
			newDialog.css("position", "absolute")
			newDialog.css("left", offset.left - 225);
			newDialog.css("top",  offset.top + button.height() );
			newDialog.css("z-index", "5000");
			dialog = newDialog;
		}
		dialog.show();

		activePopup = new ActivePopup( buttonElement, dialogId, dialog );
	}
}

/**
 *  Closes the currently active voteDialog.
 */
function closeVoteDialog( dialogId ) {
	window.status = "close "+dialogId;
	var activeDialog = $("#"+dialogId).remove();

	if (activePopup != null) {
		setHover( activePopup.button, false );
		activePopup = null;
	}

	return false;
}


/**
 *  Simply sets the desired hover attributes of the button.
 */
function enterInlineBox( button ) {
	setHover( button, true );
}

/**
 *  Checks if there is an active popup that corresponds to the button being exited.
 *  If one exists, do nothing.  Otherwise, unset the desired hover attributes.
 */
function exitInlineBox( button ) {
	if( activePopup == null || button != activePopup.button ) {
		setHover( button, false);
	}
}

/**
 * Sets the desired hover attributes based upon whether a hover is indicated or not.
 */
function setHover( button, isHover ) {
	var x = $(button);
	if( isHover ) {
		x.css("background-position", "-59px 0");
		x.children("a").css("color", "white");
	} else {
		x.css("background-position", "0 0");
		x.children("a").css("color", "black");
	}
}


/****  The following are only used by the popup windows.  ****/
/**
 * Sets the hash of the parent frame to indicate the current popup should be closed.
 */
function signalParentToCloseDialog( dialogId ) {
	// need to get the parent's location
	pl = unescape(location.href.substr(location.href.indexOf('puri=')+5));
	parent.location = pl+"#closeDialog=" + dialogId;
	//window.parent.closeVoteDialog( dialogId)
}

function UserVote( vote ) {
	this.vote = vote;
}
var userVote;

if (grail_prevVoteValue != null) {
	userVote = new UserVote(grail_prevVoteValue);
} else {
	userVote = new UserVote(0);
}

$(document).ready(function() {
	var sliderControl = $("#sliderControl");

	//If there is a slider control on the page, set it up to work correctly.
	//if( sliderControl.length > 0 ) {
	if (sliderControl != null) {
		sliderControl.slider(
		{
			min: -21,
			max: 21,
			slide: function(event, ui)
			{
				var awayName = $(".away-team").html();
				var homeName = $(".home-team").html();
				var userScoreDiv = $(".user-score");

				//var homeTeamScoreDiv = $("#homeTeamScore");
				//var awayTeamScoreDiv = $("#awayTeamScore");

				var newSliderValue = ui.value;
				var value = Math.round(newSliderValue);

				if (newSliderValue < 0) {
					userScoreDiv.html(awayName+" by "+Math.abs(newSliderValue));
					//awayTeamScoreDiv.val(value);
					//homeTeamScoreDiv.val("");
				} else if (newSliderValue > 0) {
					userScoreDiv.html(homeName+" by "+Math.abs(newSliderValue));
					//awayTeamScoreDiv.val("");
					//homeTeamScoreDiv.val("+" + value);
				} else {
					userScoreDiv.html("Even Matchup");
					//homeTeamScoreDiv.val("");
					//awayTeamScoreDiv.val("");
				}
			}
		});

		$('#sliderControl').slider("moveTo", userVote.vote);

		$("#info").ajaxError(function(event, request, settings) {
			$(this).html("Failed!");
		});
		$("#info").ajaxSuccess(function(event, request, settings) {
			$(this).html("Submitted!");
		});
	}
});

/**
 * Sends the indicated game vote to the backend. Open the confirm popup on vote completion
 */
function setGameVote() {
	var voteType = $("#voteType").html();
	var sportId = $("#sportId").html();
	var gameId = $("#gameId").html();
	var vote = $("#sliderControl").slider("value");
	var homeName = $(".home-team").html();
	var awayName = $(".away-team").html();
	var feedbackText = "";

	$.get("http://insider.espn.go.com/grail/inline/vote" , { sportId: sportId, gameId: gameId, voteType: voteType, vote: vote },
		function(data) {
			//replace the contents of the popup with a confirmation message
			feedbackBox = $(".insider-line-dialog .feedback");
			if (feedbackBox.length != 0) {
				feedbackBox.empty();
				if (vote < 0) {
					feedbackText = jQuery.trim(awayName+" by "+Math.abs(vote));
				} else if (vote > 0) {
					feedbackText = jQuery.trim(homeName+" by "+vote);
				} else {
					feedbackText = "Even matchup";
				}
				feedbackBox.append("Your prediction <span style=\"color: #F8AA14; font-weight: bold;\">("+feedbackText+")</span> has been recorded. Come back anytime before the game to update.");
				setTimeout("signalParentToCloseDialog('ctrl_"+sportId+"_"+gameId+"_"+voteType+"')", 1500);
			}
		}
	);
}

function clearInputIf(objId, checkVal) {
	var obj = $("#"+objId);
	if (obj.length != 0 && obj.val() == checkVal) obj.val("");
}
