var gamecastGameId;
var numPlayLines = 1;
var playFilterType = -1;
var isPlayoffGame;
var limitPlays = true;
var homeColor1 = "ccc";
var homeColor2 = "333";
var awayColor1 = "ccc";
var awayColor2 = "333";

function getPreferences() {
	linePref = getCookie("nhl_gamecast_numPlayLines");

	if (linePref != null && linePref != "undefined") {
		linePrefInt = parseInt(linePref);

		if (!isNaN(linePrefInt)) {
			btn = $("#lines_dd .btn_"+linePref);
			changeNumLines(btn,linePrefInt);
		}
	}
}

function setPreferences(name, value) {
	setCookie(name, value, null);
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name + "=" + escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function setColors(h1, h2, a1, a2) {
	homeColor1 = h1;
	homeColor2 = (h2.toLowerCase() != "ffffff") ? h2:"000000";
	awayColor1 = a1;
	awayColor2 = (a2.toLowerCase() != "ffffff") ? a2:"000000";

	applyColors();
}

function applyColors() {
	$(".pp_box_home").attr("style", "background-color: #"+homeColor1+"; border-bottom: 3px solid #"+homeColor2+"; border-top: 3px solid #"+homeColor2);
	$(".pp_box_away").attr("style", "background-color: #"+awayColor1+"; border-bottom: 3px solid #"+awayColor2+"; border-top: 3px solid #"+awayColor2);

}


function getPeriodString(period) {
	if (period <= 3) {
		return parseInt(period).toOrdinal();
	} else if (isPlayoffGame) {
		if (period == 4) { return "OT";}
		else {
			return (period-3)+"OT";
		}
	} else {
		if (period == 4) { return "OT";}
		if (period == 5) { return "SO";}
	}

	return "";
}

function updateGame(gameId, gameIndicies, gameData) {

	if (gameId == gamecastGameId) {
		//update game header
		gameHeaderVars = new Array('homeScore', 'awayScore');

		for(v in gameHeaderVars) {
			cName = gameHeaderVars[v];
			gameStatus = (gameData['status'] == undefined) ? 1:parseInt(gameData['status']);

			if (gameStatus != 1 && gameData[cName] != undefined) {
				cell = $(".matchup_"+cName);
				if (cell.html() != gameData[cName] && gameData[cName] != "null") {
					cell.html(gameData[cName]);
				}
			}
		}

	}

	if (gameData['clock'] == "0:00") {
		gameData['clock'] = "End";
	}

	if (gameData['clock'] == "Final") {
		if (gameData['period'] != undefined && gameData['period'] > 3) {
			gameData['period'] = getPeriodString(parseInt(gameData['period']));
		} else {
			gameData['period'] = "";
		}
	} else if (gameData['period'] != undefined) {
		if (gameData['period'] == 0) {
			gameData['period'] = "ET";
		} else {
			gameData['period'] = getPeriodString(parseInt(gameData['period']));
		}
	}

	//update oot
	ootObj = $("#nhl_oots_"+gameId);
	ootNames = new Array("clock", "period");

	if (ootObj.length > 0) {
		for(i=0; i<gameIndicies.length; i++) {

			if (ootNames.contains(gameIndicies[i])) { cellName = "oots-"+gameIndicies[i]; }
			else {cellName = gameIndicies[i];}

			obj = ootObj.find("."+cellName);

			if (obj != null && gameData[gameIndicies[i]] != undefined && gameData[gameIndicies[i]] != "null" &&  obj.html() != gameData[gameIndicies[i]].toString()) {
				//if (window.console) { console.log("Updating "+gameId+" "+gameIndicies[i]+" to "+gameData[gameIndicies[i]]); }
				obj.html(gameData[gameIndicies[i]]);

				if (cellName == "homeScore" || cellName == "awayScore") {
					obj.addClass("hl");
					setTimeout("$('#nhl_oots_"+gameId+"').find('."+cellName+"').removeClass('hl')", 3000);
				}
			}
		}
	}
}

function updatePlayer(playerId, isGoalie, playerIndicies, playerData) {

	rosterRow = $("#roster_player_"+playerId);
	var checkOrder = false;

	if (rosterRow.length > 0) {
		//player exists
		for(i=0; i<playerIndicies.length; i++) {
			var cellName = playerIndicies[i];
			statName = cellName.replace("ytd", "").toLowerCase();
			rosterData = rosterRow.find("."+statName);
			if (rosterData.length > 0) {
				if (statName == "playername") {
					htmlContent = '<a href="/nhl/players/profile?playerId='+playerId+'">'+playerData[cellName]+'</a>';
				} else if (statName == "toi") {
					checkOrder = true;
					htmlContent = secondsToClock(playerData[cellName])+' <span class="toi_seconds" style="display:none;">'+playerData[cellName]+'</span>';
				} else if (statName == "plusminus") {
					htmlContent = (playerData[cellName] > 0) ? "+"+playerData[cellName]:playerData[cellName];
				} else if (statName == "goalsagainst") {
					htmlContent = parseFloat(playerData[cellName]).toFixed(1);
				} else if (statName == "savepct") {
					savePct = (playerData[cellName].substring(0,1) == ".") ? parseFloat("0"+playerData[cellName]):parseFloat(playerData[cellName]);
					htmlContent = (savePct <= 1) ? savePct.toFixed(3):(savePct/100).toFixed(3);
				} else if (playerData[statName] == 0) {
					htmlContent = "&nbsp;";
				} else {
					htmlContent = playerData[cellName];
				}

				contentSpan = (cellName.indexOf("ytd") >= 0) ? "season_stat":"game_stat";
				rosterData.find("."+contentSpan).html(htmlContent);

				if (cellName != "toi") {
					rosterData.addClass("hl");
					setTimeout("$('#roster_player_"+playerId+"').find('."+cellName+"').removeClass('hl')", 3000);
				}
			}
		}

		//Check if we need to re-sort if toi has been adjusted
		if (checkOrder) {
			rowAbove = rosterRow.prev(".roster_player");

			if (rowAbove.length > 0) {
				toi = parseInt(rosterRow.find(".toi_seconds").html());

				if (!isNaN(toi)) {
					while (rowAbove.length > 0) {
						aboveData = rowAbove.find(".toi_seconds").html();

						if (aboveData != '' && aboveData != '&nbsp;') {
							toiAbove = parseInt(aboveData);
							if (isNaN(toiAbove) || toiAbove >= toi) { break;}
						}
						nextRow = rowAbove.prev(".roster_player");

						//check if we are at the top
						if (nextRow.length == 0) {
							rowAbove = rowAbove.prev(".roster_header");
							break;
						}

						rowAbove = nextRow;
					}
				}

				if (rowAbove != rosterRow.prev(".roster_player")) {
					rosterTbl = rosterRow.parent().parent();
					rowAbove.after(rosterRow.clone());
					rosterRow.remove();
					alternateRows("#"+rosterTbl.attr("id"), "roster_player");
				}
			}
		}
	} else {
		//add the player
		if (isGoalie) {
			addGoalie(playerId, playerData);
		} else {
			addPlayer(playerId, playerData);
		}
	}

}

function updateGoal(playId, isDelete, goalData) {
	if (isDelete) {
		removeScoringPlay(playId);
	} else {
		updateLastScoringPlay(playId, goalData);
	}
}

function updatePlay(playId, playIndicies, playData) {
	updatePlayByPlay(playId, playIndicies, playData);
	if (playData.eventType != 505) {
		updateLastPlay(playId, playIndicies, playData);
	}
}

function updateLastScoringPlay(playId, goalData) {
	scoringRow = $("#last_play_scoring_"+playId);

	if (scoringRow.length > 0) {
		//goal already exists

		for (cellName in goalData) {

			goalCell = scoringRow.find("."+cellName);
			if (goalCell.length > 0 ) {
				if (cellName == "period") {
					htmlContent = makePeriodText(goalData[cellName]);
				} else if (cellName == "clock") {
					period = (goalData['period'] != undefined) ? goalData['period']:1;
					htmlContent = reverseClock(goalData[cellName], period);
				} else if (goalData[cellName] == "null") {
					htmlContent = "&nbsp;";
				} else {
					htmlContent = goalData[cellName];
				}

				if (goalData.notifyUser) {
					highlight("#last_play_"+playId+" ."+cellName, 3000, "hl");
				}

				goalCell.html(htmlContent);
			}
		}
	} else {
		//add the goal

		eventType = goalData.eventType || '';
		period = goalData.period || '';
		//clocks coming from playbyplay count up so reverse it
		clock = reverseClock(goalData.clock, period);
		teamAbbrev = goalData.teamAbbrev || '';
		playText = (goalData.playText == "null") ? '':goalData.playText;
		goalStrength = goalData.strength || '';
		teamImg = (teamAbbrev != '') ? '<img src="http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/'+teamAbbrev+'.gif" width="25" />':'';
		goalLine = goalData.goalLine;
		assistLine = goalData.assistLine;

		var strengthHTML = "";
		if (goalStrength != '' && goalStrength != 'null') {
			boxTeam = (goalData["ppTeam"] == undefined) ? goalData["shTeam"]:goalData["ppTeam"];
			strengthHTML = makePowerPlayBox(boxTeam, goalStrength);
		}

		lastPlayTable = $(".last_play_tbl tr");
		var trHTML = [
			'<tr id="last_play_scoring_'+playId+'" class="play goal playtype_scoring">',
				'<td width="21%" nowrap="nowrap">',
					strengthHTML,
					'<div style="float:left;">',
						'<span class="period" style="color:#868686;">'+makePeriodText(period)+'</span>',
						'<span class="periodNum" style="display:none;">'+period+'</span> <strong class="clock">'+clock+'</strong>',
					'</div>',
					'<div style="clear:both;"></div>',
				'</td>',
				'<td width="1%" class="teamImg">'+teamImg+'</td>',
				'<td class="goalText" valign="top"><span class="goalLine">'+goalLine+'</span><br /><span class="assistLine">'+assistLine+'</span></td>',
			'</tr>'
		].join('');

		if (lastPlayTable.length > 0) {
			rowNum = 0;
			lastPlayTable.each(function() {
				if (rowNum < lastPlayTable.length) {
					curClock = $(this).find(".clock").html();
					curPeriod = $(this).find(".periodNum").html();
					curPlayId = parseInt($(this).attr("id").replace("last_play_", ""));

					if (isEarlier(curPeriod, curClock, period, clock) > 0) {
						trObj = $(trHTML);
						$(this).before(trObj);
						return false;
					} else if (rowNum == lastPlayTable.length-1) {
						trObj = $(trHTML);
						$(".last_play_tbl").append(trObj);
						return false;
					}
				}
				rowNum++;
			});

		} else {
			trObj = $(trHTML).appendTo(".last_play_tbl");
		}
	}
}

function removeScoringPlay(playId) {
	$("#last_play_scoring_"+playId).remove();
}

function updateLastPlay(playId, playIndicies, playData) {

	playRow = $("#last_play_"+playId);

	if (playRow.length > 0) {
		//play already exists
		for(i=0; i<playIndicies.length; i++) {
			rowName = playIndicies[i];

			playCell = playRow.find("."+rowName);
			if (playCell.length > 0 ) {
				if (rowName == "period") {
					htmlContent = makePeriodText(playData[rowName]);
					playRow.find(".periodNum").html(playData[rowName]);
				} else if (rowName == "clock") {
					period = (playData['period'] != undefined) ? playData['period']:1;
					htmlContent = reverseClock(playData[rowName], period);
				} else if (playData[rowName] == "null") {
					htmlContent = "&nbsp;";
				} else {
					htmlContent = playData[rowName];
				}

				if (playData.notifyUser) {
					highlight("#last_play_"+playId+" ."+rowName, 3000, "hl");
				}

				playCell.html(htmlContent);
			}
		}

		//update the event type
		if (playData['eventType'] != undefined && !playRow.hasClass("playtype_"+playData['eventType'])) {
			playRow.removeClass("playtype_505");	//incase a goal gets overturned
			playRow.addClass("playtype_"+playData['eventType']);
		}

		//add in the image if teamabbrev comes in
		imgObj = playRow.find(".teamImg img");
		if (playData['teamAbbrev'] != undefined) {
			if (imgObj.length == 0) {
				playRow.find(".teamImg").append('<img src="http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/'+playData['teamAbbrev']+'.gif" width="25" />');
			} else {
				imgObj.attr("src", "http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/"+playData['teamAbbrev']+".gif");
			}
		}

	} else {

		//add the play

		eventType = playData.eventType || '';
		period = playData.period || '';
		//clocks coming from playbyplay count up so reverse it
		clock = reverseClock(playData.clock, period);
		teamAbbrev = playData.teamAbbrev || '';
		playText = (playData.playText == "null") ? '':playData.playText;
		playStrength = playData.strength || '';
		teamImg = (teamAbbrev != '') ? '<img src="http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/'+teamAbbrev+'.gif" width="25" />':'';

		var strengthHTML = "";
		if (playStrength != '' && playStrength != 'null') {
			strengthHTML = makePowerPlayBox(playData["ppTeam"], "PP");
		}

		lastPlayTable = $(".last_play_tbl tr");
		var trHTML = [
			'<tr id="last_play_'+playId+'" class="play playtype_'+eventType+'">',
				'<td width="21%" nowrap="nowrap">',
					strengthHTML,
					'<div style="float:left;">',
						'<span class="period" style="color:#868686;">'+makePeriodText(period)+'</span>',
						'<span class="periodNum" style="display:none;">'+period+'</span>&nbsp;<strong class="clock">'+clock+'</strong>',
					'</div>',
					'<div style="clear:both;"></div>',
				'</td>',
				'<td width="1%" class="teamImg">'+teamImg+'</td>',
				'<td class="playText">'+playText+'</td>',
			'</tr>'
		].join('');

		if (lastPlayTable.length > 0) {
			rowNum = 0;
			lastPlayTable.each(function() {
				if (rowNum < lastPlayTable.length) {
					curClock = $(this).find(".clock").html();
					curPeriod = $(this).find(".periodNum").html();
					curPlayId = parseInt($(this).attr("id").replace("last_play_", ""));
					if (isEarlier(curPeriod, curClock, period, clock) > 0) {
						trObj = $(trHTML);
						$(this).before(trObj);
						return false;
					} else if (rowNum == lastPlayTable.length-1) {
						trObj = $(trHTML);
						$(".last_play_tbl").append(trObj);
						return false;
					}
				}
				rowNum++;
			});

		} else {
			trObj = $(trHTML).appendTo(".last_play_tbl");
		}

		trimLastPlayTable();

		//notification highlight
		if (playData.notifyUser == null || playData.notifyUser) {
			highlight("#last_play_"+playId, 3000, "hl_row");
		}
	}

	filterPlays();

}

function makePowerPlayBox(ppTeam, strengthText) {

	if (strengthText == undefined) strengthText = "PP";
	color1 = (ppTeam == "home") ? homeColor1:awayColor1;
	color2 = (ppTeam == "home") ? homeColor2:awayColor2;
	boxStyle = (color1 != "" && color1 != undefined && color1 != "undefined") ? ' background-color:#'+color1+';':'';
	boxStyle += (color2 != "" && color2 != undefined && color2 != "undefined") ? ' border-bottom:3px solid #'+color2+'; border-top:3px solid #'+color2+';':'';

	return ' <span class="pp_box pp_box_'+ppTeam+'" style="'+boxStyle+'">'+strengthText+'</span>';
}

function updatePlayByPlay(playId, playIndicies, playData) {
	period = playData.period || '';
	periodTable = $("#pbp_period_"+period);

	if (periodTable.length == 0) {
		//create new period table
		periodTable = createPBPPeriod(period);
	}

	pbpRow = periodTable.find("#pbp_"+playId);

	if (pbpRow.length > 0) {
		//pbp already exists
		checkOrder = false;

		for(i=0; i<playIndicies.length; i++) {

			var cellName = playIndicies[i];
			if (cellName == "clock") {
				clockSeconds = getClockSeconds(playData[cellName]);
				pbpRow.find(".clock_seconds").html(clockSeconds);
				htmlContent = playData[cellName];
				checkOrder = true;
			} else if (cellName == "teamAbbrev") {
				imgObj = pbpRow.find(".teamImg img");
				imgSrc = "http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/"+playData[cellName]+".gif";
				//update team logos
				if (imgObj.length == 0) {
					pbpRow.find(".teamImg").append('<img src="'+imgSrc+'" width="25" />');
				} else {
					imgObj.attr("src", imgSrc);
				}

			} else {
				htmlContent = playData[cellName];
			}
		}



		if (checkOrder) {
			newRow = pbpRow.clone();
			pbpRow.remove();

			afterElem = periodTable.find(".period_header");
			while (afterElem.next().length > 0) {
				nextElem = afterElem.next();
				nextSeconds = parseInt(nextElem.find(".clock_seconds").html());
				if (isNaN(nextSeconds) || nextSeconds <= clockSeconds) { break; }
				afterElem = nextElem;
			}

			afterElem.after(newRow);

			alternateRows("#pbp_period_"+period, "play");
		}
	} else {

		//add pbp row
		eventType = playData.eventType || '';
		clock = (playData.clock == "null" || playData.clock == undefined) ? 0:playData.clock;
		clockSeconds = getClockSeconds(clock);
		teamAbbrev = playData.teamAbbrev || '';
		playText = (playData.playText == "null") ? '':playData.playText;
		periodText = getPeriodText(period);
		afterElem = periodTable.find(".period_header");

		teamImg = (teamAbbrev != "" && teamAbbrev != undefined && teamAbbrev != "null" && teamAbbrev != "undefined") ? '<img src="http://assets.espn.go.com/i/teamlogos/nhl/sml/trans/'+teamAbbrev+'.gif" width="25" />':'';

		while (afterElem.next().length > 0) {
			nextElem = afterElem.next();
			nextSeconds = parseInt(nextElem.find(".clock_seconds").html());
			if (isNaN(nextSeconds) || nextSeconds <= clockSeconds) { break; }
			afterElem = nextElem;
		}

		ppBox = "";
		if (playData["strength"] != undefined && playData["strength"] != "" && playData["strength"] != "null") {
			ppStrength = (eventType == 505) ? playData["strength"]:"PP";
			ppTeam = (playData["ppTeam"] == undefined) ? playData["shTeam"]:playData["ppTeam"];
			ppBox = makePowerPlayBox(ppTeam, ppStrength);
		}

		afterElem.after( [
			'<tr id="pbp_'+playId+'" class="play playtype_'+eventType+'">',
				'<td width="21%" nowrap="nowrap">',
					ppBox,
					'<div style="float:left;">',
						'<span style="color:#868686;">'+periodText+'</span>&nbsp;<strong class="clock">'+clock+'</strong><span class="clock_seconds" style="display:none;">'+clockSeconds+'</span>',
					'</div>',
					'<div style="clear:both;"></div>',
				'</td>',
				'<td width="6%" class="teamImg">'+teamImg+'</td>',
				'<td width="73%" class="playText">'+playText+'</td>',
			'</tr>'
		].join(''));

		alternateRows("#pbp_period_"+period, "play");
	}
}

function createPBPPeriod(period) {
	addPeriodLink(period);
	periodLongText = getPeriodLongText(period);

	periodTable = $( [
		'<table id="pbp_period_'+period+'" class="pbp_period" cellpadding="3" cellspacing="1">',
			'<tr class="period_header"><td colspan="3">'+periodLongText+'</td></tr>',
		'</table>'
	].join(''));

	return periodTable.prependTo($("#tab_playbyplay"));
}

function addPeriodLink(period) {


	if ($(".period_link_"+period).length == 0) {

		periodText = getPeriodShortText(period);
		periodLink = '<li class="period_link period_link_'+period+'" onclick="$(\'.period_link\').removeClass(\'selected\'); $(this).addClass(\'selected\'); hideClass(\'pbp_period\'); show(\'pbp_period_'+period+'\'); return false;">'+periodText+'</li>';

		$("#pbp_all_link").before(periodLink);
	}
}

function getPeriodText(period) {
	if (isPlayoffGame == undefined) {isPlayoffGame = false;}
	if (period > 3) {
		periodText = "OT"
		if (period > 4) {
			periodText = (!isPlayoffGame) ? "SO":parseInt(period-3).toOrdinal()+" "+periodText
		}
	} else {
		periodText = parseInt(period).toOrdinal()+" Period"
		periodLongText = periodText
	}

	return periodText;
}

function getPeriodLongText(period) {
	periodLongText = getPeriodText(period);
	if (periodLongText == "SO") { return "Shootout"; }
	periodLongText.replace("OT", "Overtime");
	return periodLongText;
}

function getPeriodShortText(period) {
	if (period < 4) { return period; }
	else { return getPeriodText(period); }
}

function trimLastPlayTable() {
	playCount = 0;
	$(".last_play_tbl tr").each(function() {
		if (playCount >= 10 && !$(this).hasClass("playtype_scoring")) {
			$(this).remove();
		}

		playCount++;
	});
}

function addGoalie(playerId, playerData) {


	var afterElem = $("#"+playerData['teamid']+"_goaltender_roster .goaltender_header");

	while (afterElem.next().length > 0) {
			nextElem = afterElem.next();
			//sort by TOI
			nextSeconds = parseInt(nextElem.find(".toi_seconds").html());
			if (nextSeconds < playerData['toi']) { break; }
			afterElem = nextElem;
	}

	playerNum = (playerData['number'] != '') ? '#'+playerData['number']:'';
	shotsAgainst = (playerData['shotsagainst'] == undefined) ? "&nbsp;":playerData['shotsagainst'];
	ytdShotsAgainst = (playerData['ytdShotsAgainst'] == undefined) ? "&nbsp;":playerData['ytdShotsAgainst'];
	goalsAgainst = (playerData['goalsagainst'] == undefined) ? "&nbsp;":playerData['goalsagainst'];
	ytdGoalsAgainst = (playerData['ytdGoalsAgainst'] == undefined) ? "&nbsp;":playerData['ytdGoalsAgainst'];
	saves = (playerData['saves'] == undefined) ? "&nbsp;":playerData['saves'];
	ytdSaves = (playerData['ytdSaves'] == undefined) ? "&nbsp;":playerData['ytdSaves'];
	savepct = (playerData['savepct'] == undefined) ? "&nbsp;":playerData['savepct'];
	if (savepct > 1 && savepct <= 100) { savepct = (savepct/100).toFixed(3); }
	ytdSavepct = (playerData['ytdSavepct'] == undefined) ? "&nbsp;":playerData['ytdSavepct'];
	if (ytdSavepct > 1 && ytdSavepct <= 100) { ytdSavepct = (ytdSavepct/100).toFixed(3); }
	if (playerData['toi'] == undefined) {
		toiClock = "&nbsp;";
		toi = "&nbsp;";
	} else {
		toiClock = secondsToClock(playerData['toi']);
		toi = playerData['toi'];
	}

	if (playerData['ytdToi'] == undefined) {
		ytdToiClock = "&nbsp;";
		ytdToi = "&nbsp;";
	} else {
		ytdToiClock = secondsToClock(playerData['ytdToi']);
		ytdToi = playerData['toi'];
	}

	afterElem.after( [
		'<tr id="roster_player_'+playerId+'" class="roster_player">',
			'<td style="padding:0px; width:25px;">'+playerNum+'</td>',
			'<td width="105" class="playername align_left" nowrap="nowrap"><a href="/nhl/players/profile?playerId='+playerId+'">'+playerData['playername']+'</a></td>',
			'<td class="shotsagainst"><span class="game_stat">'+shotsAgainst+'</span><span class="season_stat">'+ytdShotsAgainst+'</span></td>',
			'<td class="goalsagainst"><span class="game_stat">'+goalsAgainst+'</span><span class="season_stat">'+ytdGoalsAgainst+'</span></td>',
			'<td class="saves"><span class="game_stat">'+saves+'</span><span class="season_stat">'+ytdSaves+'</span></td>',
			'<td class="savepct"><span class="game_stat">'+savepct+'</span><span class="season_stat">'+ytdSavepct+'</span></td>',
			'<td class="toi"><span class="game_stat">'+toiClock+' <span class="toi_seconds" style="display:none;">'+toi+'</span></span><span class="season_stat">'+ytdToiClock+'</span></td>',
		'</tr>',
	].join(''));

	alternateRows("#"+playerData['teamid']+"_goaltender_roster", "roster_player");

}

function addPlayer(playerId, playerData) {
	var afterElem;

	if (playerData['position'] == '4') {
		afterElem = $("#"+playerData['teamid']+"_player_roster .defense_header");
	} else {
		afterElem = $("#"+playerData['teamid']+"_player_roster .forward_header");
	}

	while (afterElem.next().length > 0) {
		nextElem = afterElem.next();
		//sort by TOI
		nextSeconds = parseInt(nextElem.find(".toi_seconds").html());
		if (nextElem.hasClass("defense_header") || nextSeconds < playerData['toi']) { break; }
		afterElem = nextElem;
	}

	goals = (playerData['goals'] == 0 || playerData['goals'] == undefined) ? "&nbsp;":playerData['goals'];
	ytdGoals = (playerData['ytdGoals'] == undefined) ? "0":playerData['ytdGoals'];
	assists = (playerData['assists'] == 0 || playerData['assists'] == undefined) ? "&nbsp;":playerData['assists'];
	ytdAssists = (playerData['ytdAssists'] == undefined) ? "0":playerData['ytdAssists'];
	plusminus = (playerData['plusminus'] == undefined) ? "&nbsp;":playerData['plusminus'];
	if (plusminus > 0) plusminus = "+"+plusminus;
	else if (plusminus == 0) plusminus = "E"
	ytdPlusminus = (playerData['ytdPlusminus'] == undefined) ? "0":playerData['ytdPlusminus'];
	if (ytdPlusminus > 0) ytdPlusminus = "+"+ytdPlusminus;
	else if (ytdPlusminus == 0) ytdPlusminus = "E"

	totalshots = (playerData['totalshots'] == 0 || playerData['totalshots'] == undefined) ? "&nbsp;":playerData['totalshots'];
	penaltyminutes = (playerData['penaltyminutes'] == 0 || playerData['penaltyminutes'] == undefined) ? "&nbsp;":playerData['penaltyminutes'];
	ytdTotalshots = (playerData['ytdTotalshots'] == undefined) ? "0":playerData['ytdTotalshots'];
	ytdPenaltyminutes = (playerData['ytdPenaltyminutes'] == undefined) ? "0":playerData['ytdPenaltyminutes'];
	toi = (playerData['toi'] == undefined) ? 0:playerData['toi'];
	toiClock = (toi == 0 ) ? "&nbsp;":secondsToClock(toi);
	ytdToi = (playerData['ytdToi'] == undefined) ? "&nbsp;":playerData['ytdToi'];
	ytdToiClock = (ytdToi == 0) ? "&nbsp;":secondsToClock(ytdToi);


	playerNum = (playerData['number'] != '' || playerData['number'] == undefined) ? '#'+playerData['number']:'';
	playerPos = (playerData['positionAbbrev'] != '' && playerData['positionAbbrev'] != 'D') ? ' '+playerData['positionAbbrev']:'';

	afterElem.after( [
		'<tr id="roster_player_'+playerId+'" class="roster_player">',
			'<td style="padding:0px; width:25px;">'+playerNum+'</td>',
			'<td width="105" class="playername align_left" nowrap="nowrap"><a href="/nhl/players/profile?playerId='+playerId+'" target="_blank">'+playerData['playername']+'</a>'+playerPos+'</td>',
			'<td class="goals"><span class="game_stat">'+goals+'</span><span class="season_stat">'+ytdGoals+'</span></td>',
			'<td class="assists"><span class="game_stat">'+assists+'</span><span class="season_stat">'+ytdAssists+'</span></td>',
			'<td class="plusminus"><span class="game_stat">'+plusminus+'</span><span class="season_stat">'+ytdPlusminus+'</span></td>',
			'<td class="totalshots"><span class="game_stat">'+totalshots+'</span><span class="season_stat">'+ytdTotalshots+'</span></td>',
			'<td class="penaltyminutes"><span class="game_stat">'+penaltyminutes+'</span><span class="season_stat">'+ytdPenaltyminutes+'</span></td>',
			'<td class="toi"><span class="game_stat">'+toiClock+' <span class="toi_seconds" style="display:none;">'+toi+'</span></span><span class="season_stat">'+ytdToiClock+'</span></td>',
		'</tr>'
	].join(''));

	alternateRows("#"+playerData['teamid']+"_player_roster", "roster_player");

}

function alternateRows(tableId, rowClass) {
	rowCount = 0;
	$(tableId+" ."+rowClass).each( function() {
		rowClass = (rowCount % 2 == 0) ? "even":"odd";
		$(this).removeClass("even odd").addClass(rowClass);
		rowCount++;
	});
}

function reverseClock(clockVal, period) {
	clockSeconds = getClockSeconds(clockVal);


	if (clockSeconds != -1) {
		periodLength = getPeriodLength(period);
		timeLeft = Math.max(0, periodLength - clockSeconds);

		return secondsToClock(timeLeft);
	}

	return clockVal;
}

function getClockSeconds(clockStr) {
	clockParts = clockStr.split(":");

	if (clockParts.length == 2) {
		minutes = clockParts[0];
		seconds = clockParts[1];
		return parseInt(minutes)*60 + parseFloat(seconds);
	}

	return -1;
}

function secondsToClock(timeLeft) {
	minutesLeft = Math.floor(timeLeft/60);
	secondsLeft = timeLeft%60;
	if (secondsLeft < 10) { secondsLeft = "0"+secondsLeft;}

	return minutesLeft+":"+secondsLeft;
}

function isEarlier(p1Period, p1Clock, p2Period, p2Clock) {
	//this function assumes clocks are in "count down" mode
	if (p1Period < p2Period) {
		return 1;
	} else if (p1Period > p2Period) {
		return -1;
	} else {
		//which ever is larger that means it is earlier
		clockDiff = getClockSeconds(p1Clock) - getClockSeconds(p2Clock);

		if (clockDiff > 0) {
			return 1;
		} else if (clockDiff < 0) {
			return -1;
		} else {
			return 0;
		}
	}
}

function getPeriodLength(period) {
	if (period <= 3 || isPlayoffGame) {
		return (20*60);
	} else if (period == 4) {
		return (5*60);
	}

	return 0;
}

function makePeriodText(periodNum) {
	if (periodNum <= 3) {
		return periodNum.toOrdinal()+"&nbsp;Period";
	} else if (periodNum == 4) {
		return "OT";
	} else if (isPlayoffGame != null && isPlayoffGame) {
		return (periodNum-3)+"OT";
	} else if (periodNum == 5) {
		return "SO";
	}

	return "";
}

function show(elemId) {
	$("#"+elemId).show();

}

function showClass(cls) {
	$("."+cls).show();
}

function hideClass(cls) {
	$("."+cls).hide();
}

function showTab(clickedTab, tabName) {
	$(".tab_content").hide();
	$(".tab_header").hide();
	$("#tab_"+tabName).show();
	$("#header_"+tabName).show();
	$(".tab").removeClass("selected");
	$(clickedTab).addClass("selected");
}

function changeNumLines(btn, numLines) {

	$("#lines_dd div").removeClass("selected");
	if (btn != null) {
		$(btn).addClass("selected");
	}

	//Fix for switching between all scoring and selecting the number of plays to show
	if (numPlayLines == -1 && numLines != -1 && playFilterType == "scoring") {
		$(".last_play .all_scoring").removeClass("selected");
		$(".last_play .last_scoring").addClass("selected");
	}

	numPlayLines = numLines;
	setPreferences("nhl_gamecast_numPlayLines", numLines);
	filterPlays();
}

function changePlayFilter(btn, typeId, shouldLimit) {
	$(".last_play_btn").removeClass("selected");
	$(btn).addClass("selected");

	playFilterType = typeId;
	limitPlays = shouldLimit;

	filterPlays();
}

function filterPlays() {
	var lineCount = 0;
	$(".last_play_tbl .play").each(function() {
		showPlay = (playFilterType == -1 || $(this).hasClass("playtype_"+playFilterType));
		if ( (!limitPlays || lineCount < numPlayLines) && showPlay ) {
			$(this).show();
			lineCount++;
		} else {
			$(this).hide();
		}

	});
}

function highlight(elemSelector, hlTime, hlClass) {
	if (hlTime == undefined) { hlTime = 3000; }
	if (hlClass == undefined) { hlClass = "hl"; }
	$(elemSelector).addClass(hlClass);
	setTimeout("$('"+elemSelector+"').removeClass('"+hlClass+"')", hlTime);
}

Number.prototype.toOrdinal = function() {
	var n = this % 100;
	var suff = ["th", "st", "nd", "rd", "th"]; // suff for suffix
	var ord= n<21?(n<4 ? suff[n]:suff[0]): (n%10>4 ? suff[0] : suff[n%10]);
	return this + ord;
}

String.prototype.toOrdinal = function() {
	return parseInt(this).toOrdinal();
}

if (!Array.prototype.contains){
    Array.prototype.contains = function(obj){
    var len = this.length;
    for (var i = 0; i < len; i++){
      if(this[i]===obj){return true;}
    }
    return false;
  };
}

$(document).ready(function() {
	getPreferences();
});