
// Global Variables
var fantasyOpen = false;
var pageFocused = true;
var fantasyupdatetimer = null;
var int_fantasy_loaded = false;
var if_points = new Array(0,0);
var curevent = false;
var curTab = undefined;
var int_fantasy_series = null;
var int_fantasy_countdowns = new Array();
var checkOnFantasyCounter = null;

$(document).ready(function () {
	
	$.ajax({
		url: '/interactive/init/',
		type: 'GET',
		dataType: 'json',
		success: function(data) {
			if (data.status == 1) {
				$("body").append(data.html);
				curevent = data.currentevent;
				if_points[0] = data.if_points_total;
				if (curevent) {
					if_points[1] = data.if_points_event_total;
				}
			} else {
				$("#int_bar").remove();
				return;
			}
			checkOnFantasyCounter = setTimeout("checkOnFantasy()",60000);
	}});
	
	$(window).blur(function() { pageFocused = false; /*$("#debug").append("blurred @"+Date()+" - ");*/ })
	$(window).focus(function() { pageFocused = true; int_fantasy_loaded = false; updateFocus(); /*$("#debug").append("focused @"+Date()+" - ");*/ })
	
});

function toggleFantasy() {
	if (fantasyOpen) {
		fantasyOpen = false;
		$("#int_fantasy").slideUp();
		checkOnFantasyCounter = setTimeout("checkOnFantasy()",60000);
		return;
	} else {
		document.getElementById("int_fantasy_series").innerHTML = "";
		$("#int_fantasy").slideDown();
		fantasyOpen = true;
		pageFocused = true;
		int_fantasy_loaded = false;
		fantasyUpdate();
	}	
		
} // EOF openFantasy

function updateFocus() {
	
	if (fantasyOpen) {
		fantasyUpdate();
	}
	
}

function fantasyUpdate() {
		
	
	if (!fantasyOpen) {
		return;
	}
	
	if (!pageFocused) { 
		return;
	}
	
	if (fantasyupdatetimer != null) {
		clearTimeout(fantasyupdatetimer);
		fantasyupdatetimer = null;
	}
	
	$("#int_fantasy_loading_gif").show();
	$("#int_fantasy input").attr("disabled","disabled");
	
		
	$.ajax({
		url: '/interactive/fantasyUpdate/',
		type: 'GET',
		dataType: 'json',
		success: function(data) {
			formatFantasy(data);
	}});
	
} // EOF fantasyUpdate()

function formatFantasy(data) {
	
	if (data == null) {
		return;
	}
	
	switch(data.status) {
		case 0:
			// Turned off
			$("#int_bar").remove();
			return;
			break;
		case 1:
			// No current event
			$("#int_fantasy_series").html("<span class='int_fantasy_error'>No current event at the moment.</span>");
			return;
			break;
		case 2:
			// No avail series
			$("#int_fantasy_series").html("<span class='int_fantasy_error'>No series available for predictions. Check back soon!</span>");
			return;
			break;
		case 3:
			// Game/Series is unavailable
			alert("OOPS! It appears you were too late in submitting your prediction. Try getting your predictions in before the countdown.");
			return;
			break;
		case 4:
			// Already made a prediction
			alert("OOPS! It appears you already made a prediction. Nice try!");
			return;
			break;
		case 5:
			// Not logged in.
			$("#int_fantasy_series").html("<span class='int_fantasy_error'>You must be signed in to use this feature.</span>");
			return;
			break;
	}

	if (data.status == 100) {
		// Success
		
		// Check for point difference
		if (data.if_points_total != if_points[0]) {
			// New points
			data.update = true;
			ptswon = data.if_points_total - if_points[0];
			if (curevent) {
				$(".int_fantasy_points_event").html(data.if_points_event_total);
				if_points[1] = data.if_points_event_total;
			}
			$(".int_fantasy_points_total").html(data.if_points_total);
			
			if_points[0] = data.if_points_total;
			
			newFantasyPoints(ptswon);
			
		}
		
		// Check for diff num of series
		if (data.numofseries != int_fantasy_series) {
			data.update = true;
			int_fantasy_series = data.numofseries;
		}
		
		// Check if there is no content.
		if (!int_fantasy_loaded) {
			data.update = true;
		}
		
		// Get selected tab, if any.
		

		
		html = '';
		series = data.series;
		p=0;
		if (series.length > 0 && data.update) {
			
			curTab = $("#int_fantasy_serieslist h3.ui-state-active").attr("ind") * 1;
			//$("#debug").append(" - "+curTab);
			if (curTab == undefined) curTab = 0;
		
			html += "<div id='int_fantasy_serieslist'>";
			for (var s in series) {
				html += "<h3 ind='"+p+"'>Series "+series[s].se_order+": "+series[s].se_team1+" vs. "+series[s].se_team2+"</h3>";
				html += "<div><table width='98%' cellspacing='2' cellpadding='1' border='0'><tr>" +
						"<td align='center' width='40%'><img src='"+series[s].team1logo+"' alt='tl' width='100' /></td><td align='center'><h1>vs.</h1></td>" +
						"<td align='center' width='40%'><img src='"+series[s].team2logo+"' alt='tl' width='100' /></td></tr>" +
						"<tr><td class='int_fantasy_team_series_score'>"+series[s].team1score+"</td><td align='center'><em>TO</em></td><td class='int_fantasy_team_series_score'>"+series[s].team2score+"</td></tr>" +
						"<tr><td colspan='3' align='center'>";
				
				if (series[s].predictions.pr_winner != null) {
					
					if (series[s].predictions.pr_winner == 1) {
						winner = series[s].se_team1;
					} else {
						winner = series[s].se_team2;
					}
					
					html += "<em>You predicted "+winner+" will win by "+series[s].predictions.pr_scorediff+"</em>";
					
				} else {
			
					
					if (series[s].se_start < data.time && series[s].se_active == 1) {
						
						html += "Series has already begun.";
						
					} else {
						//poswin = (series.length+1)/2;
						winbybox = "<select name='scorediff'>";
						for(i = 1; i <= series[0].totalgames; i++) {
							// Create win by count
							
							winbybox += (i%2 ? "<option>"+i+"</option>" : ""); 
						}
						winbybox += "</select>";
						
						html += "<form name='prediction_"+series[s].se_ID+"' action='javascript:void(0);' onSubmit='saveSeriesPrediction(this)'>" +
								"<input type='hidden' name='se_ID' value='"+series[s].se_ID+"' /><input type='hidden' name='ev_ID' value='"+series[s].ev_ID+"' />" +
								"Who will win? Guess the winner of this series.<br />You predict that " +
								"<select name='serieswinner'><option value='1'>"+series[s].se_team1+"</option><option value='2'>"+series[s].se_team2+"</option></select> will win by <input type='text' name='scorediff' size='2' /> <input type='submit' name='submit' value='Save' /></form>";
					}
				}
				
				html += "</td></tr></table>";
				
				gamewinnerchoice = "<select name='gmwinner'><option value='1'>"+series[s].se_team1+"</option><option value='2'>"+series[s].se_team2+"</option></select>";
										
				games = series[s].games;
				activeGames = '';
				finishedGames = '';
				numOfActive = 0;
				for (var g in games) {
					
					gm_over = false;
					gm_active = false;
					content = '';
					if (games[g].gm_active == 1) {
						if (games[g].gm_start > data.time) {
							cssClass = 'int_fantasy_starting';
							gm_info = "<br /><em>Game is starting soon!</em><div id='int_fantasy_countdown_"+games[g].gm_ID+"' class='int_fantasy_countdown_time'></div>";
							sec_left = games[g].gm_start - data.time;
							countdownFantasyGame(games[g].gm_ID,sec_left);
							
						} else {
							cssClass = 'int_fantasy_active';
							gm_info = "<br />Game is currently playing.";
							gm_active = true;
						}
					} else if (games[g].gm_active == 2) {
						cssClass = 'int_fantasy_over';
						if (games[g].gm_win == 1) { 
							gmwinner =  series[s].se_team1 
							winscore = games[g].gm_team1_score + ' to '+ games[g].gm_team2_score;
						} else { 
							gmwinner =  series[s].se_team2 
							winscore = games[g].gm_team2_score + ' to '+ games[g].gm_team1_score;
						} 
						
						gm_info = "<br /><strong>Game Over</strong> | <em>"+gmwinner+" won "+winscore+"</em>";
						gm_over = true;
					} else {
						cssClass = '';
						gm_info = '';
						numOfActive++;
					}
						
					
					content += "<li gm_ID='"+games[g].gm_ID+"' class='"+cssClass+"'><strong>Game "+games[g].gm_order+": "+games[g].gm_type+" <em>on</em> "+games[g].gm_map+"</strong>"+gm_info+"<br />";
					
					/*
					if (gm_over) {
						content += "Game Over!";
					}
					*/
					
					if (games[g].predictions.pr_winner != null) {
						
						if (gm_over) {
							
							content += " Your prediction earned "+games[g].predictions.pr_points+" points.";
							
						} else {
							
							if (games[g].predictions.pr_winner == 1) {
								winner = series[s].se_team1;
							} else {
								winner = series[s].se_team2;
							}
							content += "You predicted <strong>"+winner+"</strong> will win by <strong>"+games[g].predictions.pr_scorediff+"</strong> points.";
						}
					} else if (!gm_over && !gm_active) {
						
						content += "<form name='prediction_"+games[g].gm_ID+"' action='javascript:void(0);' onSubmit='saveGamePrediction(this)'>"+gamewinnerchoice+" " +
								"<input type='hidden' name='gm_ID' value='"+games[g].gm_ID+"' /><input type='hidden' name='ev_ID' value='"+series[s].ev_ID+"' />" +
								"will win by <input type='text' name='scorediff' size='1' style='width:20px' /> points. " +
								"<input type='submit' name='submit' value='Save' /></form>";
					}
					
					content += "</li>";
					
					if (gm_over) {
						finishedGames += content;
					} else if (numOfActive < 2) {
						activeGames += content;
					}
					
				}
				
				html += "<h4>Game Spotlight</h4><ul>"+activeGames+"</ul><br /><h4>Game History</h4><ul>"+finishedGames+"</ul>";
				
				html += "</div>";
				p++;
				//html += "Series Found:"+series[s].se_team1+" vs. "+series['se_team2']+"<br />";
			}
			html += "</div>";
			
			int_fantasy_loaded = true;
			
			$("#int_fantasy_series").html(html);
			$( "#int_fantasy_serieslist" ).accordion({"animated":false, "autoHeight": false});
			$( "#int_fantasy_serieslist" ).accordion("activate", curTab);
			$("#int_fantasy input").removeAttr("disabled");
			//$("#debug").append(" - Afterset: "+curTab);
			
		}
		
		
		$("#int_fantasy_loading_gif").hide();
	
		fantasyupdatetimer = setTimeout('fantasyUpdate()',23000);
		
	} // END IF SUCCCESS
} // EOF formatFantasy

function saveGamePrediction(formID) {
	//scorediff = $(formID+" input[name='scorediff']").val()
	
	if (!($(formID).children("input[name='scorediff']").val() > 0)) {
		alert("You must put a value in the small input field to show how many points the team will win by.");
		return;
	}
	
	formData = $(formID).serialize();
	
	$("#int_fantasy input").attr("disabled","disabled");
	$("#int_fantasy_loading_gif").show();
	
	$.ajax({
		url: '/interactive/fantasySubmit/',
		type: 'GET',
		data: "type=savegame&"+formData,
		dataType: 'json',
		success: function(data) {
			int_fantasy_loaded = false;
			formatFantasy(data);
	}});
	
	
} // EOF saveGamePrediction

function saveSeriesPrediction(formID) {
	
	formData = $(formID).serialize();

	$("#int_fantasy input").attr("disabled","disabled");
	$("#int_fantasy_loading_gif").show();
	
	$.ajax({
		url: '/interactive/fantasySubmit/',
		type: 'GET',
		data: "type=saveseries&"+formData,
		dataType: 'json',
		success: function(data) {
			int_fantasy_loaded = false;
			formatFantasy(data);
	}});
	
	
} // EOF saveSeriesPrediction


function countdownFantasyGame(gm_ID,secs) {
	
	if (int_fantasy_countdowns[gm_ID] != null) {
		clearTimeout(int_fantasy_countdowns[gm_ID]);
	}
	
	remainMin = ((Math.floor(secs/60))%60).toString();
	remainSecs = ((Math.floor(secs/1))%60).toString();
	if (remainSecs.length < 2) remainSecs = "0" + remainSecs;
	
	$("#int_fantasy_countdown_"+gm_ID+"").html(remainMin+":"+remainSecs+"");
	
	secs--;
	if (secs < 1) {
		int_fantasy_loaded = false;
		pageFocused = true;
		fantasyUpdate();
	} else {
		int_fantasy_countdowns[gm_ID] = setTimeout("countdownFantasyGame("+gm_ID+"," + (secs) + ")", 999);
	}
	
} // EOF countdownFantasyGame();

function newFantasyPoints(pts) {
	$("#int_fantasy_newpoints").html(pts+"+").show().animate({bottom: 200, opacity: 0.3},4300,function() { $(this).hide().css("opacity",1).css("bottom","0px"); });
		
} // EOF newFantasyPoints

function checkOnFantasy() {
	
	if (checkOnFantasyCounter != null) {
		clearTimeout(checkOnFantasyCounter);
		checkOnFantasyCounter = null;
	}
	
	$.ajax({
		url: '/interactive/fantasyCheck/',
		type: 'GET',
		dataType: 'json',
		success: function(data) {
			if (data.status == 0) {
				$("#int_bar").remove();
				return;
			}
			
			if (data.gamestarting) {
				// Game is starting.
				$("#int_fantasy_gamestarting").html("New Game Starting!").show().animate({bottom: 200, opacity: 0.3},4300,function() { $(this).hide().css("opacity",1).css("bottom","0px"); });
			}
			
			if (data.if_points_total != if_points[0]) {
				// New points
				ptswon = data.if_points_total - if_points[0];
				if (curevent) {
					$(".int_fantasy_points_event").html(data.if_points_event_total);
					if_points[1] = data.if_points_event_total;
				}
				$(".int_fantasy_points_total").html(data.if_points_total);
				
				if_points[0] = data.if_points_total;
				
				setTimeout("newFantasyPoints('"+ptswon+"')",1000);
				
			}
				
			
			checkOnFantasyCounter = setTimeout("checkOnFantasy()",60000);
			return;
	}});
	
} // EOF checkOnFantasy


