Skip to content

Instantly share code, notes, and snippets.

@halfmanhalfdonut
Created April 15, 2016 15:06
Show Gist options
  • Save halfmanhalfdonut/3e0cc904f8f11c42d055c9e29efd8297 to your computer and use it in GitHub Desktop.
Save halfmanhalfdonut/3e0cc904f8f11c42d055c9e29efd8297 to your computer and use it in GitHub Desktop.
/** GENERATED: Fri Apr 15 07:59:53 PDT 2016 **/
(function($, settings) {
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var i, pivot = (fromIndex) ? fromIndex : 0,
length;
if (!this) {
throw new TypeError();
}
length = this.length;
if (length === 0 || pivot >= length) {
return -1;
}
if (pivot < 0) {
pivot = length - Math.abs(pivot);
}
for (i = pivot; i < length; i++) {
if (this[i] === searchElement) {
return i;
}
}
return -1;
};
}
var getCookieValue = function(key) {
var match, exp = new RegExp("(^|;) ?" + key + "=([^;]+)(;|$)", "g");
return (match = exp.exec(document.cookie)) ? match[2] : "";
};
var getParameterByName = function(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
var appsrcValue = getParameterByName("appsrc");
if (appsrcValue == "sc") {
$("body").addClass("no-header scorecenter");
}
var h = location.hostname,
isDev = (h.indexOf("test") >= 0 || h.indexOf("dev") >= 0 || h.indexOf("mast") >= 0),
isDebug = isDev && window && typeof window.console !== "undefined";
window.espn = window.espn || {};
window.espn.gamecast = {
subscribe: function(topic, handler) {
return jQuery.sub(topic, handler);
},
unsubscribe: function(handler) {
return jQuery.unsub(handler);
},
unsubscribeAll: function(topic) {
return jQuery.unsub(topic);
},
publish: function(topic, args) {
return jQuery.pub(topic, args);
},
track: function(type, values) {
if (type !== undefined && values !== undefined && typeof(values) === "object") {
if (type == "link") {
setTimeout(function() {
try {
anTrackLink(window.location, "espn", "mlbgamecast", values.info);
} catch (e) {}
}, 100);
} else {
if (type == "page" && typeof(anClearVars) === "function") {
var gameId = values.gameId;
anClearVars();
try {
s_omni.pageName = "espn:mlb:game:gamecast";
if (pn[gameId]) {
s_omni.pageName += ":" + pn[gameId];
}
s_omni.server = window.location.host;
s_omni.channel = "mlb";
s_omni.prop1 = "espn";
s_omni.prop4 = "game";
s_omni.prop5 = "espn:mlb:game:gamecast";
s_omni.prop17 = "en";
s_omni.prop25 = "baseball";
s_omni.prop26 = "mlb";
s_omni.prop30 = "n";
s_omni.hier1 = "espn:mlb:game:gamecast";
s_omni.eVar9 = "en";
s_omni.eVar13 = s_omni.pageName;
s_omni.eVar19 = "baseball";
s_omni.eVar21 = "mlb";
s_omni.events = "event21";
var s_code = s_omni.t();
} catch (e) {}
try {
pSUPERFLY.virtualPage("/mlb/gamecast?gameId=" + gameId, "MLB Gamecast | " + pn[gameId]);
} catch (e) {}
}
}
}
},
debug: function(msg) {
if (isDebug) {
try {
console.log(msg);
} catch (e) {}
}
},
findIndex: function(searchArray, searchId, searchAttr) {
var arrayLength = searchArray.length;
var index = -1;
for (var x = 0; x < arrayLength; x++) {
if (searchArray[x][searchAttr] + "" == searchId + "") {
index = x;
break;
}
}
return index;
},
checkHTML5Player: function() {
return (!(window.location.search.indexOf("version=mobile") >= 0) || $("body").hasClass("iPad") || (window.location.search.indexOf("appsrc=ocho") >= 0 && settings.lang != "es"));
},
isVideoViewable: function(video) {
var viewable = true,
platforms = video.includePlatforms ? video.includePlatforms.join().toLowerCase() : undefined,
isHandset = espn.gamecast.version.isHandset();
if (espn.gamecast.isMobile && platforms && platforms.length > 0) {
viewable = (isHandset && (platforms.indexOf("iphone") >= 0 || platforms.indexOf("handset") >= 0 || platforms.indexOf("mobile") >= 0)) || (!isHandset && (platforms.indexOf("ipad") >= 0 || platforms.indexOf("tablet") >= 0));
}
return viewable;
},
getVideoUrl: function(id) {
var appsrcObj = appMap !== undefined ? appMap[getParameterByName("appsrc")] : undefined,
suite = appsrcObj !== undefined && appsrcObj[0] ? appsrcObj[0] : "wdgespcom",
viAppId = getCookieValue("viAppId"),
vIdParam = viAppId !== "" ? "&vid=" + viAppId : "";
return "http://m.espn.go.com/general/video.mp4?videoprofile=external&id=" + id + "&suite=" + suite + vIdParam + "&player=" + encodeURIComponent("Off Deck : GameCast");
},
appsrc: appsrcValue,
master: settings.data.gamecast,
contains: function(arr, val) {
var found = false;
for (var i = 0, l = arr.length; i < l; i += 1) {
if (arr[i] == val) {
found = true;
break;
}
}
return found;
},
inningText: {
1: "1st",
2: "2nd",
3: "3rd",
4: "4th",
5: "5th",
6: "6th",
7: "7th",
8: "8th",
9: "9th",
10: "10th",
11: "11th",
12: "12th",
13: "13th",
14: "14th",
15: "15th"
},
getGameState: function(statusId) {
return espn.gamecast.gameStates[statusId] !== undefined ? espn.gamecast.gameStates[statusId] : "live";
},
gameStates: {
"2": "live",
"22": "live",
"1": "pregame",
"7": "live",
"8": "final",
"6": "pregame",
"5": "pregame",
"3": "final",
"4": "final"
},
isEmptyObject: function(o) {
var isEmpty = true;
for (var p in o) {
if (o.hasOwnProperty(p)) {
isEmpty = false;
break;
}
}
return isEmpty;
},
toOrdinal: function(n, gender) {
if (settings.lang == "es") {
var sfx = gender == "m" ? ["mo", "er", "do", "er", "to", "to", "to", "mo", "vo", "no"] : ["ma", "ra", "da", "ra", "ta", "ta", "ta", "ma", "va", "na"];
var val = n % 10;
return n + sfx[val];
} else {
var sfx = ["th", "st", "nd", "rd"];
var val = n % 100;
return n + (sfx[(val - 20) % 10] || sfx[val] || sfx[0]);
}
},
deportesMap: {
"game feed": "Info del Partido",
"live feed": "En Vivo",
plays: "Jugadas",
"scoring plays": "Puntaje",
"box score": "Numeritos",
notes: "Notas",
social: "Social",
media: "Media",
photos: "fotos",
video: "Vídeo",
hitters: "Bateadores",
ab: "AB",
r: "C",
h: "H",
rbi: "CE",
bb: "BB",
so: "K",
avg: "AVG",
pitchers: "Lanzadores",
ip: "EL",
er: "CL",
era: "EFE",
"expanded batting stats currently unavailable": "Estadísticas expandidas de bateo no están disponibles",
"expanded batting": "Bateo expandido",
"2b": "2B",
"3b": "3B",
hr: "HR",
sb: "SF",
"expanded pitching stats currently unavailable": "Estadísticas expandidas de pitcheo no están disponibles",
"expanded pitching": "Pitcheo expandido",
"ground balls-fly balls": "Roletas-Elevados",
"batters faced": "Bateadores Enfrentados",
balk: "Balk",
hbp: "Pelotazo",
ibb: "BBI",
wp: "LG",
e: "E",
"team totals": "Totales por Equipo",
today: "Hoy",
season: "Temporada",
"last season": "Últimos Temporada",
lh: "LZ",
rh: "LD",
rhp: "LD",
lhp: "LZ",
vs: "vs",
"vs lh": "vs. Zurdos",
"vs rh": "vs. Derechos",
"vs lhp": "vs LZ",
"vs rhp": "vs LD",
opponent: "Oponente",
"no stats available": "No hay registro de anotaciones disponibles",
sv: "SALV",
hld: "HLD",
tbf: "AB",
ba: "PROM OP",
"pitch count": "Conteo de pitcheos",
"hit zone on": "Encender zona de bateo",
"hit zone off": "Apagar zona de bateo",
"batting left": "Bate zurdo",
"batting right": "Bate derecho",
pitch: "Lanzamiento",
"first at bat": "Primer turno al bate",
"baserunners on": "Encender corredores en base",
"baserunners off": "Apagar corredores en base",
"defense on": "Encender defensa",
"defense off": "Apagar defensa",
"spray chart on": "Encender batazos",
"spray chart off": "Apagar batazos",
"view full box score": "Ver Ficha completa",
"view full play-by-play": "Ver todas las Jugadas",
"last play": "U. JUGADA",
"on deck": "Próximo en turno",
replay: "Repetir",
"photos received": "Fotos recibidas",
of: "de",
and: "y",
"pitching to": "Le lanza a",
"comment from": "Comentario de",
"currently unavailable": "no disponibles",
"game starts at": "Juego comienza a las",
preview: "Previa",
recap: "Crónica",
"switch to this game": "Cambiar partido",
outs: "Outs",
out: "Out",
thumbnails: "Miniaturas",
"photos currently unavailable": "Fotos no disponibles",
"scoring plays currently unavailable": "No hay registro de anotaciones disponibles",
"play-by-play currently unavailable": "No hay registro de anotaciones disponibles",
"tweets currently unavailable": "Tweets no disponibles",
"videos currently unavailable": "Videos no disponibles",
seconds: "segundos",
second: "segundo",
"projected winner": "Ganador proyectado",
"hit distribution": "Distribución de hits",
at: "en",
"due up for the": "Esperando turno por los",
"chance of scoring": "Probabilidad de anotar",
"runs this inning": "carreras en este inning",
"expected runs": "Carreras Proyectadas",
run: "carrera",
runs: "carreras",
"bases loaded": "Bases Llenas",
"bases empty": "Bases Limpias",
"runners on": "Hombres en",
"runner on": "Hombres en",
"career vs.": "de por vida en contra",
"for": "por",
"w/risp": "c/PA",
"after count": "despu&#233;s de conteo",
"this year": "este a&#241;o"
},
translate: function(str) {
var tempStr = str.toLowerCase();
if (settings.lang == "es") {
return espn.gamecast.deportesMap[tempStr] != undefined ? espn.gamecast.deportesMap[tempStr] : str;
} else {
return str;
}
},
getFullTeamName: function(team) {
var midText = "",
teamName = "";
if (settings.lang == "es") {
if (team.loc.toLowerCase() == "florida") {
midText = "de la";
} else {
if (team.loc.toLowerCase() == "chicago") {
midText = "";
} else {
midText = "de";
}
}
teamName = team.name + " " + midText + " " + team.loc;
} else {
teamName = team.loc + " " + team.name;
}
return teamName;
},
getPlayerLink: function(id, name) {
var m = "http://m.espn.go.com/mlb/playercard?playerId=",
link = "";
if (espn.gamecast.isMobile) {
link = '<a href="http://m.espn.go.com/mlb/playercard?playerId=' + id + '" class="poppable" data-playerId="' + id + '" target="_blank">' + name + "</a>";
} else {
var slug = name.replace(/[^a-zA-Z 0-9]+/g, "").split(" ").join("-").toLowerCase();
if (settings.lang.toLowerCase() == "es") {
link = '<a href="http://espndeportes.espn.go.com/beisbol/mlb/jugador/_/id/' + id + "/" + slug + '" class="poppable" data-playerId="' + id + '" target="_blank">' + name + "</a>";
} else {
link = '<a href="http://espn.go.com/mlb/player/_/id/' + id + "/" + slug + '" class="poppable" data-playerId="' + id + '" target="_blank">' + name + "</a>";
}
}
return link;
},
getPlayerLinkHREF: function(id) {
var m = "http://m.espn.go.com/nba/playercard?playerId=",
link = "";
if (espn.gamecast.isMobile) {
link = "http://m.espn.go.com/mlb/playercard?playerId=" + id;
} else {
var slug = name.replace(/[^a-zA-Z 0-9]+/g, "").split(" ").join("-").toLowerCase();
if (settings.lang.toLowerCase() == "es") {
link = "http://espndeportes.espn.go.com/beisbol/mlb/jugador/_/id/" + id + "/" + slug;
} else {
link = "http://espn.go.com/mlb/player/_/id/" + id + "/" + slug;
}
}
return link;
},
getCommentURL: function() {
if (settings.lang.toLowerCase() == "es") {
return "http://espndeportes.espn.go.com/mlb/deportes/conversacion?gameId=" + espn.gamecast.master.current.id;
} else {
return "http://scores.espn.go.com/mlb/conversation?gameId=" + espn.gamecast.master.current.id;
}
},
gotEcho: false,
gotAudio: false
};
(function(d) {
var cache = {};
d.pub = function(topic, args) {
if (cache[topic]) {
var cachedCallbacks = d.extend([], cache[topic]);
for (var i = 0, n = cachedCallbacks.length; i < n; i++) {
cachedCallbacks[i].apply(d, args || []);
}
cachedCallbacks = null;
}
};
d.sub = function(topic, callback) {
if (!cache[topic]) {
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
};
d.unsub = function(handle) {
if (handle instanceof Array && handle.length > 1) {
var t = handle[0];
cache[t] && d.each(cache[t], function(idx) {
if (this == handle[1]) {
cache[t].splice(idx, 1);
}
});
} else {
if (String(handle.constructor).indexOf("String") >= 0) {
espn.gamecast.debug("unsubscribing all callbacks from " + handle);
cache[handle] = [];
}
}
};
})(jQuery);
})(jQuery, settings);
espn.gamecast.caster = {};
(function($, settings) {
var CAST = espn.gamecast.caster,
flashVersion = swfobject.getFlashPlayerVersion(),
currentSnapshotId = 0,
sessionId = "",
isDev = (window.location.host.indexOf("test") >= 0 || window.location.host.indexOf("dev") >= 0 || window.location.host.indexOf("mast") >= 0),
baseURL = isDev ? window.location.host + "/" + settings.sport + "/caster/snapshot" : "scores.espn.go.com/" + settings.sport + "/caster/snapshot",
casterHost = isDev ? "vldchadoop02.corp.espn3.com" : "site.caster.espn.go.com",
casterPort = isDev ? 2223 : 80,
pollDuration = 15000,
casterInterval;
CAST.switchCasterSession = function() {
currentSnapshotId = espn.gamecast.master.snapshotId;
sessionId = espn.gamecast.master.sessionId;
if (flashVersion !== undefined && flashVersion.major !== undefined && flashVersion.major >= 8) {
CAST.embedFlashConnector();
} else {
CAST.startFauxCast();
}
};
CAST.embedFlashConnector = function() {
$("#caster").empty();
var casterObj = new flashObj();
casterObj.flashFile = "http://assets.espn.go.com/swf/caster/snapshotCasterClientv2.swf";
casterObj.flashVars = "sessionName=" + sessionId + "&duration=15000&pollMode=absolute&baseURL=" + baseURL + "&host=" + casterHost + "&port=" + casterPort + "&currentSnapshotId=" + currentSnapshotId;
casterObj.wmode = "window";
casterObj.width = "1";
casterObj.height = "1";
casterObj.quality = "best";
casterObj.FlashVer = 8;
casterObj.DenyIEdl = "TRUE";
casterObj.cabVersion = "8,0,0,0";
casterObj.useDOM = true;
casterObj.bgcolor = "#000000";
casterObj.targetElement = "caster";
casterObj.render(true);
};
function fauxCast(callback) {
clearInterval(casterInterval);
var snapshotURL = "/" + settings.sport + (settings.lang.toLowerCase() == "es" ? "/deportes" : "") + "/caster/json?sessionId=" + sessionId + "&masterSnap=" + currentSnapshotId + "&rand=" + new Date().getTime();
$.ajax({
type: "GET",
url: snapshotURL,
dataType: "json",
success: function(data) {
if (data !== undefined && data.snapshotId !== undefined) {
handleCasterMessage(data.snapshotId, data.snapshots);
currentSnapshotId = data.snapshotId;
}
if (typeof callback === "function") {
callback();
}
espn.gamecast.publish("updateReceived", [new Date()]);
casterInterval = setTimeout(fauxCast, pollDuration);
},
error: function() {
casterInterval = setTimeout(fauxCast, pollDuration);
}
});
}
CAST.startFauxCast = function() {
fauxCast();
};
window.handleCasterMessage = function(snapshotId, snapshots) {
if (typeof(snapshots) == "object") {
espn.gamecast.update.processSnapshots(snapshots);
}
};
CAST.handleUpdateRequest = function(callback) {
if (espn.gamecast.master.current.gameState === "live") {
fauxCast(callback);
} else {
callback();
}
};
espn.gamecast.subscribe("ready", CAST.switchCasterSession);
espn.gamecast.subscribe("requestUpdate", CAST.handleUpdateRequest);
})(jQuery, settings);
espn.gamecast.update = {};
(function($, settings) {
var UP = espn.gamecast.update,
currentGameId = 0,
ketchupPlayQueue = [],
isKetchupPlay = false,
ketchupPlayInterval, waitedForPlay = true,
PLAYDELAY = 2000;
UP.updateCurrentGameId = function() {
currentGameId = espn.gamecast.master.current.id;
};
espn.gamecast.subscribe("ready", UP.updateCurrentGameId);
UP.processSnapshots = function(snapshots, message) {
espn.gamecast.debug({
"Caster Snapshots!": snapshots
});
for (var i = 0, n = snapshots.length; i < n; i++) {
var snapshot = snapshots[i];
var snapshotKey = snapshot.objId;
if (snapshot.objId !== undefined) {
var parts = snapshot.objId.split("-"),
updateType = parts[0],
gameId = "",
playerId = "";
if (parts.length == 2) {
gameId = parts[1];
} else {
if (parts.length == 3) {
gameId = parts[2];
} else {
if (parts.length == 4) {
playerId = parts[2];
gameId = parts[3];
}
}
}
if (updateType == "oot") {
try {
UP.updateOOT(snapshot, gameId);
} catch (e) {
espn.gamecast.debug("updateOOT error: " + e);
}
}
if (updateType == "video") {
try {
UP.updateVideo(snapshot);
} catch (e) {
espn.gamecast.debug("updateVideo error: " + e);
}
}
if (gameId != currentGameId) {
continue;
}
if (updateType == "play") {
try {
var playId = parts[1];
if (message == "ketchup") {
UP.updatePlay(snapshot, playId);
} else {
ketchupPlayQueue.push({
snapshot: snapshot,
playId: playId
});
}
} catch (e) {
espn.gamecast.debug("updatePlay error" + e);
}
} else {
if (updateType == "game") {
try {
UP.updateGame(snapshot);
} catch (e) {
espn.gamecast.debug("updateGame error: " + e);
}
} else {
if (updateType == "photo") {
try {
UP.updatePhoto(snapshot);
} catch (e) {
espn.gamecast.debug("updatePhoto error: " + e);
}
} else {
if (updateType == "tweet" && (settings.lang.toLowerCase() == snapshot.objId.split("-")[1].toLowerCase())) {
try {
UP.updateTweet(snapshot);
} catch (e) {
espn.gamecast.debug("updateTweet error: " + e);
}
} else {
if (updateType == "nst") {
try {
UP.updateNST(snapshot);
} catch (e) {
espn.gamecast.debug("updateNST error: " + e);
}
} else {
if (updateType == "pitcher") {
try {
UP.updatePitcher(snapshot, playerId);
} catch (e) {
espn.gamecast.debug("updatePitcher error: " + e);
}
} else {
if (updateType == "batter") {
try {
UP.updateBatter(snapshot, playerId);
} catch (e) {
espn.gamecast.debug("updateBatter error: " + e);
}
} else {
if (updateType == "scoringPlay") {
try {
UP.updateScoringPlays(snapshot);
} catch (e) {
espn.gamecast.debug("updateScoringPlays error" + e);
}
} else {
if ((updateType == "c_en" && settings.lang == "en") || (updateType == "c_es" && settings.lang == "es")) {
try {
UP.updateCommentary(snapshot);
} catch (e) {
espn.gamecast.debug("updateCommentary error: " + e);
}
}
}
}
}
}
}
}
}
}
}
}
if (ketchupPlayQueue.length > 0) {
if (waitedForPlay) {
if (ketchupPlayInterval === undefined) {
ketchupPlayInterval = setInterval(UP.processPlayQueue, PLAYDELAY);
}
waitedForPlay = false;
setTimeout(function() {
waitedForPlay = true;
}, PLAYDELAY);
}
}
};
UP.processPlayQueue = function() {
var currentPlayObj;
if (ketchupPlayQueue.length > 0) {
espn.gamecast.debug("shiftin' length:" + ketchupPlayQueue.length);
currentPlayObj = ketchupPlayQueue.shift();
if (currentPlayObj !== undefined) {
UP.updatePlay(currentPlayObj.snapshot, currentPlayObj.playId);
}
}
espn.gamecast.debug("after length: " + ketchupPlayQueue.length);
if (ketchupPlayQueue.length == 0) {
ketchupPlayInterval = clearInterval(ketchupPlayInterval);
}
};
UP.updateGame = function(snapshot) {
var game = espn.gamecast.master.current,
en_gameIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41],
es_gameIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41],
gameIndex = settings.lang == "es" ? es_gameIndex : en_gameIndex,
gameAttr = ["statusId", "away-score", "away-hits", "away-errors", "away-record", "home-score", "home-hits", "home-errors", "home-record", "scores-away", "scores-home", "inning", "halfInning", "status1", "status2", "strikes", "balls", "outs", "bases", "seriesText", "pvb-hits", "pvb-atBats", "pvb-homeRuns", "pvb-strikeouts", "pvb-avg", "countStats-hits", "countStats-atBats", "countStats-homeRuns", "countStats-strikeouts", "countStats-avg", "rispStats-hits", "rispStats-atBats", "rispStats-homeRuns", "rispStats-strikeouts", "rispStats-avg", "expectedRunsOne", "expectedRunsTwo", "winPercentage", "gameState"],
currData, parts;
for (var i = 0, n = gameIndex.length; i < n; i++) {
currData = snapshot[gameIndex[i + ""]];
currData = currData != "null" ? currData : "";
if (currData !== undefined && currData != null) {
parts = gameAttr[i].split("-");
if (parts.length > 1) {
if (parts[0] == "scores") {
game[parts[0]][parts[1]] = currData.split("|");
} else {
game[parts[0]][parts[1]] = currData;
}
} else {
if (parts[0] == "bases") {
var bases = currData.split("|"),
playerArray;
if (bases.length == 3) {
game.onBase = [];
for (var i = 0, n = bases.length; i < n; i++) {
playerArray = bases[i].split("!@");
if (playerArray.length > 2) {
game.onBase.push({
id: playerArray[0],
firstName: playerArray[1],
lastName: playerArray[2]
});
}
}
}
} else {
if (parts[0] == "winPercentage") {
if (currData != -1) {
game[parts[0]] = currData;
}
} else {
game[parts[0]] = currData;
}
}
}
}
}
espn.gamecast.publish("gameUpdate", [game, false, true]);
};
UP.updateOOT = function(snapshot, gameId) {
var ootIndex = espn.gamecast.findIndex(espn.gamecast.master.games, gameId, "id");
if (ootIndex > -1) {
var thisGame = espn.gamecast.master.games[ootIndex],
en_oGameIndex = [0, 1, 2, 3, 4, 7, 8, 9, 10, 11],
es_oGameIndex = [0, 1, 2, 5, 6, 7, 8, 9, 10, 11],
oGameIndex = settings.lang == "es" ? es_oGameIndex : en_oGameIndex,
oGameAttr = ["gameStatus", "away-score", "home-score", "status1", "status2", "strikes", "balls", "outs", "bases", "pbpSourceId"],
currData, parts;
for (var i = 0, n = oGameIndex.length; i < n; i++) {
currData = snapshot[oGameIndex[i + ""]];
currData = currData != "null" ? currData : "";
if (currData !== undefined && currData != null) {
parts = oGameAttr[i].split("-");
if (parts.length > 1) {
thisGame[parts[0]][parts[1]] = currData;
} else {
thisGame[parts[0]] = currData;
}
}
}
var queue = thisGame.id == currentGameId ? true : false;
espn.gamecast.publish("ootUpdate", [thisGame, false, queue]);
}
};
UP.updatePlay = function(snapshot, playId) {
var newPlay = {},
playArray = snapshot["0"].split("|");
newPlay.batter = {};
newPlay.pitcher = {};
if (playArray.length > 10) {
newPlay.id = playId;
newPlay.atbatId = playArray[0];
newPlay.batter.firstName = playArray[1];
newPlay.batter.lastName = playArray[2];
newPlay.batter.id = playArray[3];
newPlay.pitcher.firstName = playArray[4];
newPlay.pitcher.lastName = playArray[5];
newPlay.pitcher.id = playArray[6];
newPlay.balls = playArray[7];
newPlay.strikes = playArray[8];
newPlay.isScore = playArray[9];
newPlay.summaryType = playArray[10];
newPlay.eventType = playArray[11];
newPlay.isResult = eval(playArray[12]);
newPlay.playType = playArray[13];
newPlay.pitchXCoord = playArray[16];
newPlay.pitchYCoord = playArray[17];
newPlay.hitXCoord = playArray[18];
newPlay.hitYCoord = playArray[19];
newPlay.trajectory = playArray[20];
newPlay.outs = playArray[21];
newPlay.pitcher.hand = playArray[22];
newPlay.batter.hand = playArray[23];
newPlay.awayScore = playArray[24];
newPlay.homeScore = playArray[25];
newPlay.winPercentage = playArray[26];
newPlay.halfInning = playArray[27];
newPlay.expectedRunsOne = playArray[30];
newPlay.expectedRunsTwo = playArray[31];
newPlay.timeStamp = playArray[32];
newPlay.velocity = playArray[33];
var playIndex = espn.gamecast.findIndex(espn.gamecast.master.plays, playId, "id"),
spliceIndex = 0,
spliceNumber = 0,
newNote = true;
if (playIndex >= 0) {
spliceNumber = 1;
spliceIndex = playIndex;
newNote = false;
}
if (settings.lang == "es") {
newPlay.playResult = playArray[15];
newPlay.inningText = playArray[29];
} else {
newPlay.playResult = playArray[14];
newPlay.inningText = playArray[28];
}
espn.gamecast.master.plays.splice(spliceIndex, spliceNumber, newPlay);
espn.gamecast.publish("playUpdate", [newPlay, newNote, true]);
}
};
UP.createPitcherSplits = function(innings, oppAvg, strikeouts, era, wins, losses, saves, holds, battersFaced) {
this.innings = innings;
this.oppAvg = oppAvg;
this.strikeouts = strikeouts;
this.era = era;
this.wins = wins;
this.losses = losses;
this.saves = saves;
this.holds = holds;
this.battersFaced = battersFaced;
};
UP.createPitcher = function(id, firstName, lastName, country, state, position, isStarter, hand, number, replacedBy, forPlayerId) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.country = country;
this.state = state;
this.isStarter = isStarter;
this.hand = hand;
this.replacedBy = replacedBy;
this.forPlayerId = forPlayerId;
this.today = {
inningsPitched: "-",
hits: "-",
runs: "-",
er: "-",
walks: "-",
strikeouts: "-",
homeruns: "-",
pitches: "-",
strikes: "-",
era: "-",
wildPitches: "-",
intentionalWalks: "-",
battersHit: "-",
balks: "-",
battersFaced: "-",
groundBallFlyBall: "-"
};
this.season = new UP.createPitcherSplits("-", "-", "-", "-", "-", "-", "-", "-", "-");
this.lastSeason = new UP.createPitcherSplits("-", "-", "-", "-", "-", "-", "-", "-", "-");
this.vsLH = new UP.createPitcherSplits("-", "-", "-", "-", "-", "-", "-", "-", "-");
this.vsRH = new UP.createPitcherSplits("-", "-", "-", "-", "-", "-", "-", "-", "-");
this.awayHomeStats = new UP.createPitcherSplits("-", "-", "-", "-", "-", "-", "-", "-", "-");
this.number = number;
};
UP.updatePitcher = function(snapshot, playerId) {
var team = snapshot.objId.split("-")[1],
playerIndex = espn.gamecast.findIndex(espn.gamecast.master.pitching[team], playerId, "id"),
attr = ["firstName", "lastName", "position", "isStarter", "hand", "number", "forPlayerId", "replacedBy", "today-inningsPitched", "today-hits", "today-runs", "today-er", "today-walks", "today-strikeouts", "today-homeruns", "today-pitches", "today-strikes", "today-era", "today-wildPitches", "today-intentionalWalks", "today-battersHit", "today-balks", "today-battersFaced", "today-groundBallFlyBall"],
attrLength = attr.length,
newPitcher = false,
player, parts, currData;
if (playerIndex == -1) {
playerIndex = espn.gamecast.master.pitching[team].push(new UP.createPitcher(playerId, "", "", "", "", "", "", "", "", "", "")) - 1;
newPitcher = true;
}
player = espn.gamecast.master.pitching[team][playerIndex];
for (var i = 0, n = attr.length; i < n; i++) {
currData = snapshot[i + ""];
if (currData !== undefined && currData != "null" && currData != null) {
parts = attr[i].split("-");
if (parts.length > 1) {
player[parts[0]][parts[1]] = currData;
} else {
player[parts[0]] = currData;
}
}
}
var splitCats = ["season", "lastSeason", "vsLH", "vsRH", "awayHomeStats"],
splitAttr = ["innings", "oppAvg", "strikeouts", "era", "wins", "losses", "saves", "holds", "battersFaced"];
var snapIndex;
for (var i = 0, n = splitCats.length; i < n; i++) {
for (var x = 0, y = splitAttr.length; x < y; x++) {
snapIndex = (y * i) + attrLength + x;
if (snapshot[snapIndex + ""] !== undefined && snapshot[snapIndex + ""] != "null" && snapshot[snapIndex + ""] != null) {
player[splitCats[i]][splitAttr[x]] = snapshot[snapIndex + ""];
}
}
}
espn.gamecast.publish("pitcherUpdate", [player, newPitcher, true]);
};
UP.createBatterSplits = function(atBats, runs, hits, doubles, triples, homeRuns, RBIs, walks, stolenBases, strikeouts, avg, onBasePct, slugAvg) {
this.atBats = atBats;
this.runs = runs;
this.hits = hits;
this.doubles = doubles;
this.triples = triples;
this.homeRuns = homeRuns;
this.RBIs = RBIs;
this.walks = walks;
this.stolenBases = stolenBases;
this.strikeouts = strikeouts;
this.avg = avg;
this.onBasePct = onBasePct;
this.slugAvg = slugAvg;
};
UP.createBatter = function(id, firstName, lastName, bats, country, state, batOrder, position, isStarter, forPlayerId, replacedBy, isPinchHitter, isPinchRunner, number) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.bats = bats;
this.country = country;
this.state = state;
this.batOrder = batOrder;
this.position = position;
this.isStarter = isStarter;
this.forPlayerId = forPlayerId;
this.replacedBy = replacedBy;
this.isPinchHitter = isPinchHitter;
this.isPinchRunner = isPinchRunner;
this.today = {
atBats: "",
runs: "",
hits: "",
doubles: "",
triples: "",
homeRuns: "",
RBIs: "",
walks: "",
stolenBases: "",
strikeouts: "",
avg: ""
};
this.season = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.lastSeason = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.vsLH = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.vsRH = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.awayHomeStats = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.vsOpp = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.monthStats = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.playoffStats = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.careerStats = new UP.createBatterSplits("", "", "", "", "", "", "", "", "", "", "", "", "");
this.hitzone = ["", "", "", "", "", "", "", "", ""];
this.sprayZone = {
infLeftPct: "",
infMidPct: "",
infRightPct: "",
outLeftPct: "",
outMidPct: "",
outRightPct: ""
};
this.number = number;
};
UP.updateBatter = function(snapshot, playerId) {
var team = snapshot.objId.split("-")[1],
playerIndex = espn.gamecast.findIndex(espn.gamecast.master.batting[team], playerId, "id"),
attr = ["firstName", "lastName", "position", "jersey", "bats", "isStarter", "batOrder", "forPlayerId", "replacedBy", "isPinchHitter", "isPinchRunner", "today-atBats", "today-runs", "today-hits", "today-doubles", "today-triples", "today-homeRuns", "today-RBIs", "today-walks", "today-stolenBases", "today-strikeouts", "today-avg", "hitzone-0", "hitzone-1", "hitzone-2", "hitzone-3", "hitzone-4", "hitzone-5", "hitzone-6", "hitzone-7", "hitzone-8", "sprayZone-infLeftPct", "sprayZone-infMidPct", "sprayZone-infRightPct", "sprayZone-outLeftPct", "sprayZone-outMidPct", "sprayZone-outRightPct"],
attrLength = attr.length,
newBatter = false,
needToSort = false,
player, currData;
if (playerIndex == -1) {
playerIndex = espn.gamecast.master.batting[team].push(new UP.createBatter(playerId, "", "", "", "", "", "", "", "", "", "", "", "", "")) - 1;
newBatter = true;
needToSort = true;
}
player = espn.gamecast.master.batting[team][playerIndex];
for (var i = 0, n = attr.length; i < n; i++) {
currData = snapshot[i + ""];
if (currData !== undefined && currData != "null" && currData != null) {
parts = attr[i].split("-");
if (parts.length > 1) {
player[parts[0]][parts[1]] = currData;
} else {
if (parts[0] == "batOrder") {
needToSort = true;
}
player[parts[0]] = currData;
}
}
}
var splitCats = ["season", "lastSeason", "vsLH", "vsRH", "awayHomeStats", "vsOpp", "monthStats", "playoffStats", "careerStats"],
splitAttr = ["atBats", "runs", "hits", "doubles", "triples", "homeRuns", "RBIs", "walks", "stolenBases", "strikeouts", "avg", "onBasePct", "slugAvg"];
var snapIndex;
for (var i = 0, n = splitCats.length; i < n; i++) {
for (var x = 0, y = splitAttr.length; x < y; x++) {
snapIndex = (y * i) + attrLength + x;
if (snapshot[snapIndex + ""] !== undefined && snapshot[snapIndex + ""] != "null" && snapshot[snapIndex + ""] != null) {
player[splitCats[i]][splitAttr[x]] = snapshot[snapIndex + ""];
}
}
}
if (needToSort) {
espn.gamecast.master.batting[team].sort(function(a, b) {
if (a.batOrder === undefined || a.batOrder == "") {
return 1;
} else {
return parseInt(a.batOrder, 10) - parseInt(b.batOrder, 10);
}
});
}
espn.gamecast.publish("batterUpdate", [player, newBatter, true]);
};
UP.nst = function(id, note) {
this.id = id;
this.note = note;
};
UP.updateNST = function(snapshot) {
var noteId = snapshot.objId.split("-")[1],
note = snapshot["0"],
noteIndex = espn.gamecast.findIndex(espn.gamecast.master.nst, noteId, "id"),
spliceIndex = 0,
spliceNumber = 0,
newNote = true;
noteObj = new UP.nst(noteId, note);
if (noteIndex >= 0) {
spliceNumber = 1;
spliceIndex = noteIndex;
newNote = false;
}
espn.gamecast.master.nst.splice(spliceIndex, spliceNumber, noteObj);
espn.gamecast.publish("nstUpdate", [noteObj, newNote, false]);
};
UP.photo = function(photoId, timeStamp, text, img, largeImg) {
this.photoId = photoId;
this.timeStamp = timeStamp;
this.text = text;
this.img = img;
this.largeImg = largeImg;
};
UP.updatePhoto = function(snapshot) {
var photoId = snapshot.objId.split("-")[1],
img = snapshot["0"].split("|")[0],
text = snapshot["0"].split("|")[1],
timeStamp = snapshot["0"].split("|")[2],
largeImg = snapshot["0"].split("|")[3],
photoIndex = espn.gamecast.findIndex(espn.gamecast.master.photos, photoId, "photoId"),
photoObj = new UP.photo(photoId, timeStamp, text, img, largeImg),
newPhoto = true;
if (photoIndex >= 0) {
newPhoto = false;
espn.gamecast.master.photos.splice(photoIndex, 1, photoObj);
} else {
espn.gamecast.master.photos.push(photoObj);
}
espn.gamecast.publish("photoUpdate", [photoObj, newPhoto, false]);
};
UP.tweet = function(tweetId, timeStamp, userName, text, img, isESPNTalent, displayName, isRetweet, origUserName, origDisplayName, origProfileImage) {
this.tweetId = tweetId;
this.timeStamp = timeStamp;
this.userName = userName;
this.text = text.indexOf("&lt;") >= 0 ? $("<p>" + text + "</p>").text() : text;
this.img = img;
this.isESPNTalent = eval(isESPNTalent);
this.displayName = displayName;
this.isRetweet = isRetweet;
this.original = {
userName: origUserName,
displayName: origDisplayName,
img: origProfileImage
};
};
UP.updateTweet = function(snapshot) {
var tweetId = snapshot.objId.split("-")[2],
img = snapshot["0"].split("|")[0],
text = snapshot["0"].split("|")[1],
userName = snapshot["0"].split("|")[2],
timeStamp = snapshot["0"].split("|")[3],
isESPNTalent = snapshot["0"].split("|")[4],
displayName = snapshot["0"].split("|")[5],
isRetweet = snapshot["0"].split("|")[6] || false,
origUserName = snapshot["0"].split("|")[7] || "",
origDisplayName = snapshot["0"].split("|")[8] || "",
origProfileImage = snapshot["0"].split("|")[9] || "",
tweetIndex = espn.gamecast.findIndex(espn.gamecast.master.tweets, tweetId, "tweetId"),
spliceIndex = 0,
spliceNumber = 0,
tweetObj = new UP.tweet(tweetId, timeStamp, userName, text, img, isESPNTalent, displayName, isRetweet, origUserName, origDisplayName, origProfileImage),
newTweet = true;
if (tweetIndex >= 0) {
spliceNumber = 1;
spliceIndex = tweetIndex;
newTweet = false;
}
espn.gamecast.master.tweets.splice(spliceIndex, spliceNumber, tweetObj);
espn.gamecast.publish("tweetUpdate", [tweetObj, newTweet, true]);
};
UP.scoringPlay = function(atbatId, playId, playResult, inningText, homeScore, awayScore) {
this.atbatId = atbatId;
this.playId = playId;
this.playResult = playResult;
this.inningText = inningText;
this.homeScore = homeScore;
this.awayScore = awayScore;
this.pitches = [];
};
UP.scoringPlayPitch = function(playId, pitchResult) {
this.playId = playId;
this.pitchResult = pitchResult;
};
UP.updateScoringPlays = function(snapshot) {
var atbatId = snapshot.objId.split("-")[1],
playId = snapshot.objId.split("-")[2],
abArray = snapshot["0"].split("|"),
inningText = settings.lang == "es" ? abArray[1] : abArray[0],
awayScore = abArray[2],
homeScore = abArray[3],
playResult = settings.lang == "es" ? abArray[5] : abArray[4],
playArray = abArray[6].split("!@"),
spIndex = espn.gamecast.findIndex(espn.gamecast.master.scoringPlays, playId, "playId"),
spliceNumber = 0,
spliceIndex = 0,
newScoringPlay = new UP.scoringPlay(atbatId, playId, playResult, inningText, homeScore, awayScore),
newSP = true,
pitchId, pitchResult, pitches;
for (var i = 0, n = playArray.length; i < n; i++) {
pitches = playArray[i].split("$!");
if (pitches.length > 1) {
pitchId = pitches[0];
pitchResult = pitches[1];
newScoringPlay.pitches.push(new UP.scoringPlayPitch(pitchId, pitchResult));
}
}
if (spIndex >= 0) {
spliceNumber = 1;
spliceIndex = spIndex;
newSP = false;
}
espn.gamecast.master.scoringPlays.splice(spliceIndex, spliceNumber, newScoringPlay);
espn.gamecast.publish("spUpdate", [newScoringPlay, newSP, true]);
};
UP.commentaryMsg = function(id, isHost, author, message, minute, avatar) {
this.id = id;
this.isHost = isHost;
this.author = author;
this.message = message;
this.minute = minute;
this.avatar = avatar;
};
UP.updateCommentary = function(snapshot) {
var cilMessageInfoString = snapshot["0"],
cilMessageArray = cilMessageInfoString.split("|");
if (cilMessageArray.length == 6) {
var id = cilMessageArray[0],
isHost = cilMessageArray[1],
author = cilMessageArray[2],
message = cilMessageArray[3],
minute = cilMessageArray[4],
avatar = cilMessageArray[5],
cilIndex = espn.gamecast.findIndex(espn.gamecast.master.commentary.comments, id, "id"),
newCIL = true,
spliceIndex = 0,
spliceNumber = 0,
cilObj = new UP.commentaryMsg(id, isHost, author, message, minute, avatar);
if (cilIndex >= 0) {
spliceNumber = 1;
spliceIndex = cilIndex;
newCIL = false;
}
espn.gamecast.master.commentary.comments.splice(spliceIndex, spliceNumber, cilObj);
espn.gamecast.publish("comUpdate", [cilObj, newCIL, false]);
}
};
UP.video = function(id, title, description, length, thumbnail, includePlatforms, photo, gameId, isStoryVideo) {
this.id = id;
this.title = title;
this.description = description;
this.length = length;
this.thumbnail = thumbnail;
this.includePlatforms = includePlatforms;
this.photo = photo;
this.gameId = gameId;
};
UP.updateVideo = function(snapshot) {
var vidArray = snapshot[0].split("|");
if (vidArray.length >= 5) {
var id = vidArray[0],
title = vidArray[1],
description = vidArray[2],
length = vidArray[3],
thumbnail = vidArray[4],
includePlatforms = vidArray.length >= 6 ? vidArray[5].split(",") : [],
photo = vidArray.length >= 7 ? vidArray[6] : "",
isStoryVideo = vidArray.length >= 8 ? vidArray[7] : false,
gameId = snapshot.objId.split("-").length >= 3 ? snapshot.objId.split("-")[2] : 0,
vidIndex = espn.gamecast.findIndex(espn.gamecast.master.videos, id, "id"),
newVideo = true,
spliceIndex = 0,
spliceNumber = 0,
newVidObj = new UP.video(id, title, description, length, thumbnail, includePlatforms, photo, gameId, isStoryVideo);
if (vidIndex >= 0) {
spliceNumber = 1;
spliceIndex = vidIndex;
newVideo = false;
}
espn.gamecast.master.videos.splice(spliceIndex, spliceNumber, newVidObj);
espn.gamecast.publish("videoUpdate", [newVidObj, newVideo, false]);
}
};
})(jQuery, settings);
espn.gamecast.header = {};
(function($) {
var HEAD = espn.gamecast.header;
HEAD.update = function() {
HEAD.builders.matchup();
HEAD.builders.linescore();
HEAD.builders.awayBox();
HEAD.builders.homeBox();
$("body").removeClass("live final pregame").addClass(espn.gamecast.getGameState(espn.gamecast.master.current.statusId));
};
HEAD.builders = {
matchup: function() {
var awayTeam = espn.gamecast.master.current.away,
homeTeam = espn.gamecast.master.current.home,
atText = settings.lang == "es" ? "visita a" : "at";
outputHTML = '<h1 class="matchup">' + espn.gamecast.getFullTeamName(awayTeam) + " " + (awayTeam.record != "&nbsp;" ? awayTeam.record : "") + " " + atText + " " + espn.gamecast.getFullTeamName(homeTeam) + " " + (homeTeam.record != "&nbsp;" ? homeTeam.record : "") + '</h1><h2 class="tv">';
if (espn.gamecast.master.current.seriesText && espn.gamecast.master.current.seriesText != "") {
outputHTML += espn.gamecast.master.current.seriesText + " ";
}
if (espn.gamecast.master.current.tvText != "") {
outputHTML += "TV: " + espn.gamecast.master.current.tvText;
}
outputHTML += "</h2>";
$("#game-overview").html(outputHTML);
},
linescore: function() {
var endInning = espn.gamecast.master.current.inning > 9 ? espn.gamecast.master.current.inning : 9,
startInning = espn.gamecast.master.current.inning > 10 ? espn.gamecast.master.current.inning - 10 : 1,
currInning = espn.gamecast.master.current.inning,
team, scores, teamString;
var outputHTML = '<table cellspacing="0"><thead><tr><td class="team">&nbsp;</td>';
for (var i = startInning; i <= endInning; i++) {
outputHTML += "<td>" + i + "</td>";
}
outputHTML += '<td>&nbsp;</td><td class="rhe">' + espn.gamecast.translate("R") + '</td><td class="rhe">' + espn.gamecast.translate("H") + '</td><td class="rhe">' + espn.gamecast.translate("E") + "</td></tr></thead><tbody>";
for (var i = 0; i < 2; i++) {
if (i == 0) {
team = espn.gamecast.master.current.away;
scores = espn.gamecast.master.current.scores.away;
teamString = "away";
} else {
team = espn.gamecast.master.current.home;
scores = espn.gamecast.master.current.scores.home;
teamString = "home";
}
outputHTML += '<tr class="' + teamString + '-line"><td class="team">' + team.abbrev.toUpperCase() + "</td>";
for (var x = startInning; x <= endInning; x++) {
var inningClass = x == currInning && espn.gamecast.master.current.statusId != 3 ? "currInn" : "";
outputHTML += '<td class="' + inningClass + '">' + scores[x - 1] + "</td>";
}
outputHTML += '<td class="spacer">&nbsp;</td><td class="rhe">' + team.score + '</td><td class="rhe">' + team.hits + '</td><td class="rhe">' + team.errors + "</td>";
}
outputHTML += "</tbody>";
"</table>";
$("#linescore").html(outputHTML);
},
awayBox: function() {
var awayTeam = espn.gamecast.master.current.away,
scoreClass = espn.gamecast.master.current.gameState === "pregame" && espn.gamecast.isMobile ? "rotatingScore record" : "rotatingScore",
scoreText = espn.gamecast.master.current.gameState === "pregame" && espn.gamecast.isMobile ? awayTeam.record : awayTeam.score,
outputHTML = '<div class="team-name vteamname" style="background-color:' + awayTeam.color + ';">' + (espn.gamecast.master.current.isAllStarGame ? awayTeam.loc.toUpperCase() : awayTeam.name.toUpperCase() ? awayTeam.name.toUpperCase() : espn.gamecast.getFullTeamName(awayTeam).toUpperCase()) + '</div><div class="score-info"><div class="logo-medium vlogo"><img src="' + awayTeam.logo + '" /></div><div class="score"><div class="' + scoreClass + '">' + scoreText + "</div></div></div>";
$("#awayScoreBox").html(outputHTML);
},
homeBox: function() {
var homeTeam = espn.gamecast.master.current.home,
scoreClass = (espn.gamecast.master.current.gameState === "pregame" && espn.gamecast.isMobile) ? "rotatingScore record" : "rotatingScore",
scoreText = (espn.gamecast.master.current.gameState === "pregame" && espn.gamecast.isMobile) ? homeTeam.record : homeTeam.score,
outputHTML = '<div class="team-name hteamname" style="background-color:' + homeTeam.color + ';">' + (espn.gamecast.master.current.isAllStarGame ? homeTeam.loc.toUpperCase() : homeTeam.name.toUpperCase() ? homeTeam.name.toUpperCase() : espn.gamecast.getFullTeamName(homeTeam).toUpperCase()) + '</div><div class="score-info"><div class="score"><div class="' + scoreClass + '">' + scoreText + '</div></div><div class="logo-medium hlogo"><img src="' + homeTeam.logo + '" /></div></div>';
$("#homeScoreBox").html(outputHTML);
},
projWinner: function() {
var winPercentage = espn.gamecast.master.current.winPercentage < 0 || espn.gamecast.master.current.winPercentage == "" ? 50 : parseFloat(espn.gamecast.master.current.winPercentage) * 100,
homeTeam = espn.gamecast.master.current.home,
awayTeam = espn.gamecast.master.current.away,
homePct = parseInt(winPercentage, 10),
awayPct = parseInt(100 - winPercentage),
winningTeamClass = winPercentage < 50 ? "visitor-team" : "home-team",
winningTeamClass = homePct === 50 ? "even" : winningTeamClass,
outputHTML = '<div class="proj-winner ' + winningTeamClass + '"><div class="winner-arrows"><div class="winner-arrow away"></div><div class="label">' + espn.gamecast.translate("Projected Winner") + '</div><div class="winner-arrow home"></div></div><div class="winner-shade home" style="background-color:' + homeTeam.color + ';"></div><div class="winner-shade visitor" style="background-color:' + awayTeam.color + ';"></div><p class="winner-team visitor">' + awayTeam.name.toUpperCase() + " <span>" + awayPct + '%</span></p><p class="winner-team home">' + homeTeam.name.toUpperCase() + " <span>" + homePct + "%</span></p></div>";
$("#projWinner").html(outputHTML);
}
};
})(jQuery);
espn.gamecast.activityFeed = {};
(function($) {
var AF = espn.gamecast.activityFeed,
incrementPhotos = false,
isPhotoDelayed = false,
numCurrPhotos = 0;
AF.update = function(data, type) {
if (type == "play") {
var play = data;
if (play.playResult != "null" && (play.summaryType == "P" || play.summaryType == "N" || play.summaryType == "S" || play.summaryType == "C" || play.summaryType == "A" || play.eventType == 58)) {
if (play.playType == "play" || (!play.isResult && play.outs == 3 && play.playType == "atbat")) {
var playIndex = espn.gamecast.findIndex(AF.feed, play.id, "playId"),
newPlay = new AF.builders.json.play(play.id, play.playResult + " " + play.velocity, "", play.eventType, play.inningText, play.timeStamp);
if (playIndex > -1) {
AF.feed.splice(playIndex, 1, newPlay);
$("#af_play-" + play.id).replaceWith(AF.builders.html.play(newPlay));
} else {
AF.feed.splice(0, 0, newPlay);
$("#activityFeed").children("ul").prepend(AF.builders.html.play(newPlay));
}
} else {
var atbatIndex = espn.gamecast.findIndex(AF.feed, play.atbatId, "atbatId"),
result = "";
if (atbatIndex > -1) {
result = eval(play.isResult) ? play.playResult : AF.feed[atbatIndex].result;
var isScore = eval(play.isScore) ? play.isScore : AF.feed[atbatIndex].isScore;
var newAtBat = new AF.builders.json.atbat(play.atbatId, play.batter.firstName, play.batter.lastName, play.batter.id, play.pitcher.firstName, play.pitcher.lastName, play.pitcher.id, result, AF.feed[atbatIndex].pitches, isScore, play.inningText, play.timeStamp),
pitchIndex = espn.gamecast.findIndex(AF.feed[atbatIndex].pitches, play.id, "playId"),
newPitch = new AF.builders.json.pitch(play.id, eval(play.isScore), play.summaryType, play.playResult + " " + play.velocity, play.isResult);
if (pitchIndex > -1) {
AF.feed[atbatIndex].pitches.splice(pitchIndex, 1, newPitch);
} else {
AF.feed[atbatIndex].pitches.push(newPitch);
}
AF.feed.splice(atbatIndex, 1, newAtBat);
$("#af_atbat-" + play.atbatId).replaceWith(AF.builders.html.atbat(newAtBat, true));
} else {
result = eval(play.isResult) ? play.playResult : "";
var newPitch = new AF.builders.json.pitch(play.id, eval(play.isScore), play.summaryType, play.playResult + " " + play.velocity, play.isResult),
newAtBat = new AF.builders.json.atbat(play.atbatId, play.batter.firstName, play.batter.lastName, play.batter.id, play.pitcher.firstName, play.pitcher.lastName, play.pitcher.id, result, [newPitch], eval(play.isScore), play.inningText, play.timeStamp);
AF.feed.splice(0, 0, newAtBat);
$("#activityFeed ul li.atBat").removeClass("expanded");
$("#activityFeed").children("ul").prepend(AF.builders.html.atbat(newAtBat, true));
}
}
}
} else {
if (type == "tweet") {
var tweet = data,
tweetIndex = espn.gamecast.findIndex(AF.feed, tweet.tweetId, "tweetId"),
newTweet = new AF.builders.json.tweet(tweet.tweetId, tweet.text, tweet.img, tweet.userName, tweet.timeStamp, tweet.displayName);
if (tweetIndex > -1) {
AF.feed.splice(tweetIndex, 1, newTweet);
$("#af_tweet-" + tweet.tweetId).replaceWith(AF.builders.html.tweet(newTweet));
} else {
AF.feed.splice(0, 0, newTweet);
$("#activityFeed").children("ul").prepend(AF.builders.html.tweet(newTweet));
}
} else {
if (type == "photo") {
var photo = data,
photoIndex = espn.gamecast.findIndex(AF.feed, photo.photoId, "photoId"),
newPhoto = new AF.builders.json.photo(photo.photoId, photo.img, photo.text, photo.timeStamp);
if (photoIndex > -1) {
AF.feed.splice(photoIndex, 1, newPhoto);
$("#af_photo-" + photo.photoId).replaceWith(AF.builders.html.photo(newPhoto));
} else {
AF.feed.splice(0, 0, newPhoto);
if (!incrementPhotos) {
isPhotoDelayed = true;
setTimeout(function() {
$("#activityFeed").children("ul").prepend(AF.builders.html.photo(newPhoto));
isPhotoDelayed = false;
}, 10000);
numCurrPhotos++;
incrementPhotos = true;
setTimeout(function() {
incrementPhotos = false;
numCurrPhotos = 0;
}, 300000);
} else {
numCurrPhotos++;
AF.incrementPhotoCount();
}
}
}
}
}
};
AF.build = function() {
AF.feed = [];
var plays = espn.gamecast.master.plays,
tweets = espn.gamecast.master.tweets,
photos = espn.gamecast.master.photos,
photoIndex = 0,
tweetIndex = 0,
outputHTML = "",
numTweets = tweets != undefined ? tweets.length : 0,
numPhotos = photos != undefined ? photos.length : 0,
feedItems = AF.feed,
currentPitches = [],
result = "",
isScore = false,
isResult = false,
feedItem;
for (var i = plays.length - 1; i >= 0; i--) {
if (plays[i].summaryType == "A") {
currentPitches = [];
result = "";
isScore = false;
isResult = false;
atbatTimestamp = plays[i].timeStamp;
for (var x = i - 1; x >= 0; x--) {
if (plays[x].eventType == 57 && (plays[x].summaryType == "N" || plays[x].summaryType == "S") && (plays[x + 1].strikes == 3 || plays[x + 1].balls == 4 || plays[x + 1].playResult.indexOf("in play") >= 0 || plays[x + 1].playResult.toLowerCase().indexOf("en juego") >= 0)) {
isResult = true;
result = plays[x].playResult;
isScore = plays[x].isScore;
atbatTimestamp = plays[x].timeStamp;
currentPitches.push(new AF.builders.json.pitch(plays[x].id, isScore, plays[x].summaryType, plays[x].playResult + " " + plays[x].velocity, isResult));
i--;
} else {
if (plays[x].eventType == 57 && plays[x].outs == 3) {
break;
} else {
currentPitches.push(new AF.builders.json.pitch(plays[x].id, isScore, plays[x].summaryType, plays[x].playResult + " " + plays[x].velocity, isResult));
i--;
}
}
if (isResult) {
break;
}
}
feedItems.push(new AF.builders.json.atbat(plays[i].atbatId, plays[i].batter.firstName, plays[i].batter.lastName, plays[i].batter.id, plays[i].pitcher.firstName, plays[i].pitcher.lastName, plays[i].pitcher.id, result, currentPitches, isScore, plays[i].inningText, atbatTimestamp));
} else {
feedItems.push(new AF.builders.json.play(plays[i].id, plays[i].playResult + " " + plays[i].velocity, "", plays[i].eventType, plays[i].inningText, plays[i].timeStamp));
}
}
feedItems.reverse();
var numItems = feedItems.length + numPhotos + numTweets;
for (var i = 0; i < numItems; i = i + 2) {
if (i % 4 == 0 && tweetIndex < numTweets) {
if (tweets[tweetIndex] !== undefined) {
feedItems.splice(i, 0, new AF.builders.json.tweet(tweets[tweetIndex].tweetId, tweets[tweetIndex].text, tweets[tweetIndex].img, tweets[tweetIndex].userName, tweets[tweetIndex].timeStamp, tweets[tweetIndex].displayName));
tweetIndex++;
}
} else {
if (i % 4 == 2 && photoIndex < numPhotos) {
feedItems.splice(i, 0, new AF.builders.json.photo(photos[photoIndex].photoId, photos[photoIndex].img, photos[photoIndex].text, photos[photoIndex].timeStamp));
photoIndex++;
}
}
}
feedItems = feedItems.sort(AF.sortFeed);
var countingPhotos = false,
displayItemIndex;
for (var i = 0, n = feedItems.length; i < n; i++) {
feedItem = feedItems[i];
if (countingPhotos) {
if (feedItem.type !== "photo") {
outputHTML += AF.builders.html.photo(feedItems[i - 1], false);
countingPhotos = false;
outputHTML += AF.builders.html[feedItem.type](feedItem, false);
numCurrPhotos = 0;
} else {
numCurrPhotos++;
}
} else {
if (feedItem.type === "photo") {
countingPhotos = true;
displayItemIndex = i;
numCurrPhotos++;
} else {
outputHTML += AF.builders.html[feedItem.type](feedItem, false);
}
}
}
if (numCurrPhotos !== 0 && displayItemIndex !== undefined) {
outputHTML += AF.builders.html.photo(feedItems[(displayItemIndex + numCurrPhotos) - 1], false);
}
numCurrPhotos = 0;
$("#activityFeed").html("<ul>" + outputHTML + "</ul>");
$("#activityFeed").children("ul").children("li.atBat:first").addClass("expanded");
var $title = $("#activityFeed ul li.atBat .expander");
$title.die();
$title.live("click", function(e) {
e.preventDefault();
var $this = $(this);
$this.siblings("ul.pitches").slideToggle("fast", function() {
if ($(this).is(":hidden")) {
$this.parent().removeClass("expanded");
} else {
$this.parent().addClass("expanded");
}
});
});
};
AF.builders = {
html: {
atbat: function(feedItem, isExpanded) {
var title = feedItem.result != "" ? "<span class='inning'>" + feedItem.inningText + ":</span> " + feedItem.result : "<span class='inning'>" + feedItem.inningText + ":</span> " + feedItem.pitcher.firstName + " " + feedItem.pitcher.lastName + " " + espn.gamecast.translate("pitching to") + " " + feedItem.batter.firstName + " " + feedItem.batter.lastName,
outputHTML = "",
scoringClass = feedItem.isScore ? "scoring-play" : "",
expandedClass = isExpanded ? "expanded" : "";
outputHTML += '<li id="af_atbat-' + feedItem.atbatId + '" class="feed-mod play atBat ' + scoringClass + " " + expandedClass + '"><a href="#" class="expand-arrow expander"></a><p class="play-text expander"><a href="#">' + title + '</a></p><ul class="pitches">';
for (var n = 0, i = feedItem.pitches.length - 1; i >= n; i--) {
outputHTML += this.pitch(feedItem.pitches[i]);
}
outputHTML += "</ul></li>";
return outputHTML;
},
play: function(feedItem) {
if (feedItem.text == "null") {
return "";
} else {
if (feedItem.eventType == "58") {
return '<li id="af_play-' + feedItem.playId + '"><h2 class="inning-header">' + feedItem.text + "</h2></li>";
} else {
if (feedItem.eventType != "59" && feedItem.text.trim() != "null") {
return '<li id="af_play-' + feedItem.playId + '" class="feed-mod play"><p class="play-text"><span class="inning">' + feedItem.inningText + ":</span> " + feedItem.text + "</p></li>";
} else {
return "";
}
}
}
},
tweet: function(feedItem) {
if (feedItem !== undefined) {
return '<li id="af_tweet-' + feedItem.tweetId + '" class="feed-mod tweet"><div class="twit-pic"><a href="https://twitter.com/' + feedItem.userName + '" target="_blank"><img src="' + feedItem.img + '" width="48" height="48" border="0" title="' + feedItem.userName + '" alt="' + feedItem.userName + '" class="post-img" /></a></div><div class="twit-content"><div class="twit-header"><span class="twit-time"><a href="https://twitter.com/' + feedItem.userName + "/status/" + feedItem.tweetId + '" target="_blank">' + AF.getTimeSince(feedItem.timeStamp) + '</a></span><a href="https://twitter.com/" target="_blank"><img src="http://a.espncdn.com/i/gamecast/twitter/twitter-logo.png" class="twitter-logo" /></a><span class="twit-name"><a href="https://twitter.com/' + feedItem.userName + '" target="_blank">' + feedItem.displayName + '</a></span><span class="twit-handle">@<a href="https://twitter.com/' + feedItem.userName + '" target="_blank">' + feedItem.userName + '</a></span></div><p class="twit-text">' + AF.linkitup(feedItem.text.replace(/&amp;#|&#x26;#/g, "&#")) + '</p><div class="twit-footer">' + AF.getTwitterLinks(feedItem) + '</div></div><div class="clear"></div></li>';
} else {
return "";
}
},
photo: function(feedItem) {
var displayText = feedItem.text.length > 250 ? feedItem.text.substring(0, feedItem.text.indexOf(" ", 230)) + "..." : feedItem.text,
photoCount = numCurrPhotos > 1 ? '<span class="photoCount">1 ' + espn.gamecast.translate("of") + " " + numCurrPhotos + " " + espn.gamecast.translate("Photos Received") + "<br/></span>" : '<span class="photoCount"></span>';
return '<li id="af_photo-' + feedItem.photoId + '" class="feed-mod photo video"><a href="#" class="launchGallery"><img width="110" src="' + feedItem.img + '" title="' + feedItem.text + '" onerror="this.src=\'http://a.espncdn.com/combiner/i?img=broadband/video/images/thumb_default_576.gif&w=110\'" /></a><p class="vid-date">' + photoCount + displayText + "</p></li>";
},
pitch: function(pitch) {
var outputHTML = "";
if (pitch.text.trim() != "null" && !eval(pitch.isResult) && pitch.summaryType != "A") {
outputHTML += '<li id="af_play-' + pitch.playId + '"><p>' + pitch.text + "</p></li>";
}
return outputHTML;
}
},
json: {
atbat: function(atbatId, batterFirstName, batterLastName, batterId, pitcherFirstName, pitcherLastName, pitcherId, result, pitches, isScore, inningText, timeStamp) {
this.atbatId = atbatId;
this.batter = {};
this.batter.firstName = batterFirstName;
this.batter.lastName = batterLastName;
this.batter.id = batterId;
this.pitcher = {};
this.pitcher.firstName = pitcherFirstName;
this.pitcher.lastName = pitcherLastName;
this.pitcher.id = pitcherId;
this.result = result;
this.pitches = pitches;
this.type = "atbat";
this.isScore = isScore;
this.inningText = inningText;
this.timeStamp = timeStamp;
return this;
},
play: function(playId, text, img, eventType, inningText, timeStamp) {
this.playId = playId;
this.text = text;
this.img = img;
this.eventType = eventType;
this.inningText = inningText;
this.type = "play";
this.timeStamp = timeStamp;
return this;
},
tweet: function(tweetId, text, img, userName, timeStamp, displayName) {
this.tweetId = tweetId;
this.img = img;
this.text = text;
this.userName = userName;
this.displayName = displayName;
this.timeStamp = timeStamp;
this.type = "tweet";
return this;
},
photo: function(photoId, img, text, timeStamp) {
this.photoId = photoId;
this.img = img;
this.text = text;
this.timeStamp = timeStamp;
this.type = "photo";
return this;
},
pitch: function(playId, isScore, summaryType, text, isResult) {
this.playId = playId;
this.isScore = isScore;
this.summaryType = summaryType;
this.text = text;
this.isResult = isResult;
return this;
}
}
};
AF.feed = [];
AF.sortFeed = function(a, b) {
return parseInt(b.timeStamp, 10) - parseInt(a.timeStamp, 10);
};
AF.replay = function(playId) {
if (playId !== undefined) {
var rePlayIndex = espn.gamecast.findIndex(espn.gamecast.master.plays, playId, "id"),
rePlay = rePlayIndex >= 0 ? espn.gamecast.master.plays[rePlayIndex] : undefined;
if (rePlay !== undefined) {
var resultIndex = espn.gamecast.findIndex(espn.gamecast.activityFeed.feed, rePlay.atbatId, "atbatId");
espn.gamecast.activityFeed.replayResult = resultIndex >= 0 ? espn.gamecast.activityFeed.feed[resultIndex].result : "";
try {
espn.gamecast.publish("replay", [{
type: rePlay.trajectory,
x: rePlay.hitXCoord,
y: rePlay.hitYCoord,
eventType: rePlay.eventType,
result: AF.replayResult
}]);
} catch (e) {
espn.gamecast.debug("error: " + e);
}
}
}
};
AF.replayResult = "";
AF.handleReplayComplete = function() {
AF.replayResult = "";
};
AF.incrementPhotoCount = function() {
if (numCurrPhotos > 1 && !isPhotoDelayed) {
$("#activityFeed li.photo:first").find(".photoCount").replaceWith('<span class="photoCount">1 ' + espn.gamecast.translate("of") + " " + numCurrPhotos + " " + espn.gamecast.translate("Photos Received") + "<br/></span>");
}
};
AF.getTwitterLinks = function(tweet) {
var linkHTML = '<ul class="twit-actions">',
actions = [{
link: "https://twitter.com/intent/tweet?in_reply_to=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/reply.png",
text: "Reply",
imgClass: ""
}, {
link: "https://twitter.com/intent/retweet?tweet_id=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/retweet.png",
text: "Retweet",
imgClass: "retweet"
}, {
link: "https://twitter.com/intent/favorite?tweet_id=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/fav.png",
text: "Favorite",
imgClass: ""
}];
for (var i = 0, n = actions.length; i < n; i++) {
linkHTML += '<li class="twit-action">';
linkHTML += '<a href="' + actions[i].link + '" target="_blank"><img src="' + actions[i].img + '" class="' + actions[i].imgClass + '"/> ' + actions[i].text + "</a>";
linkHTML += "</li>";
}
linkHTML += "</ul>";
return linkHTML;
};
AF.linkitup = function(text) {
var returnText = text;
returnText = returnText.replace(/@(\w*(?!<))/g, function(m1, m2) {
return ' @<a href="https://twitter.com/' + $.trim(m2) + '" target="_blank">' + $.trim(m2) + "</a> ";
});
returnText = returnText.replace(/((^|\s)\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(m1) {
return ' <a href="' + $.trim(m1) + '" target="_blank">' + $.trim(m1) + "</a> ";
});
returnText = returnText.replace(/(^|\s)#(\w*(?!<))/g, function(m1, m2, m3) {
return ' #<a href="https://twitter.com/search?q=%23' + $.trim(m3) + '&src=hash" target="_blank">' + $.trim(m3) + "</a> ";
});
return returnText;
};
AF.bindTweetLinks = function() {
if (espn.gamecast.isMobile) {
$("#activityFeed ul").off().on("click", ".tweet a", function(e) {
var $this = $(this);
e.preventDefault();
window.open($this.attr("href"), "twittersharer", "scrollbars=0");
});
}
};
AF.getTimeSince = function(timeStr) {
var date = new Date((parseInt(timeStr, 10) || "")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) {
return "";
}
return day_diff == 0 && (diff < 3600 && Math.floor(diff / 60) + "m" || diff < 86400 && Math.floor(diff / 3600) + " h") || day_diff < 7 && day_diff + "d" || day_diff < 31 && Math.ceil(day_diff / 7) + "w";
};
espn.gamecast.subscribe("replayComplete", AF.handleReplayComplete);
})(jQuery);
espn.gamecast.battingSplits = {};
(function($) {
var SPLITS = espn.gamecast.battingSplits,
currentIndex = 0,
splitInterval;
SPLITS.build = function(splits, init) {
if (splits != undefined && splits.length > 0) {
SPLITS.splits = splits;
if (init) {
currentIndex = 0;
clearInterval(splitInterval);
} else {
currentIndex = currentIndex >= SPLITS.splits.length ? 0 : currentIndex;
}
$("#rotating-splits").html("<p>" + SPLITS.splits[currentIndex] + "</p>");
if (init) {
splitInterval = setInterval("espn.gamecast.battingSplits.animate()", 8000);
}
} else {
$("#rotating-splits").html("");
}
};
SPLITS.splits = [];
SPLITS.animate = function() {
var nextIndex = currentIndex + 1 == SPLITS.splits.length ? 0 : currentIndex + 1;
if (SPLITS.splits.length > 0) {
$("#rotating-splits").children("p").fadeOut(250, function() {
var $this = $(this);
$this.html(SPLITS.splits[nextIndex]);
$this.fadeIn(250);
currentIndex = nextIndex;
});
}
};
})(jQuery);
espn.gamecast.pbp = {};
(function($) {
var PBP = espn.gamecast.pbp;
PBP.update = function(data) {
var play = data;
espn.gamecast.debug("recieved play:" + play.playResult);
if (play.playResult != "null" && (play.summaryType == "P" || play.summaryType == "N" || play.summaryType == "S" || play.summaryType == "A" || play.eventType == 58)) {
if (play.playType == "play" || (!play.isResult && play.outs == 3 && play.playType == "atbat")) {
var playIndex = espn.gamecast.findIndex(PBP.feed, play.id, "playId"),
newPlay = new PBP.builders.json.play(play.id, play.playResult + " " + play.velocity, "", play.eventType, play.inningText);
if (playIndex > -1) {
PBP.feed.splice(playIndex, 1, newPlay);
$("#pbp_play-" + play.id).replaceWith(PBP.builders.html.play(newPlay));
} else {
PBP.feed.splice(0, 0, newPlay);
$("#playbyplay").children("ul").prepend(PBP.builders.html.play(newPlay));
}
} else {
var atbatIndex = espn.gamecast.findIndex(PBP.feed, play.atbatId, "atbatId"),
result = "";
if (atbatIndex > -1) {
result = eval(play.isResult) ? play.playResult : PBP.feed[atbatIndex].result;
var isScore = eval(play.isScore) ? play.isScore : PBP.feed[atbatIndex].isScore,
newAtBat = new PBP.builders.json.atbat(play.atbatId, play.batter.firstName, play.batter.lastName, play.batter.id, play.pitcher.firstName, play.pitcher.lastName, play.pitcher.id, result, PBP.feed[atbatIndex].pitches, isScore, play.inningText),
pitchIndex = espn.gamecast.findIndex(PBP.feed[atbatIndex].pitches, play.id, "playId"),
newPitch = new PBP.builders.json.pitch(play.id, eval(play.isScore), play.summaryType, play.playResult + " " + play.velocity, play.isResult);
if (pitchIndex > -1) {
PBP.feed[atbatIndex].pitches.splice(pitchIndex, 1, newPitch);
} else {
PBP.feed[atbatIndex].pitches.push(newPitch);
}
$("#pbp_atbat-" + play.atbatId).replaceWith(PBP.builders.html.atbat(newAtBat, true));
} else {
result = eval(play.isResult) ? play.playResult : "";
var newPitch = new PBP.builders.json.pitch(play.id, eval(play.isScore), play.summaryType, play.playResult + " " + play.velocity, play.isResult),
newAtBat = new PBP.builders.json.atbat(play.atbatId, play.batter.firstName, play.batter.lastName, play.batter.id, play.pitcher.firstName, play.pitcher.lastName, play.pitcher.id, result, [newPitch], eval(play.isScore), play.inningText);
$("#playbyplay ul li.atBat").removeClass("expanded lastAtBat");
PBP.feed.splice(0, 0, newAtBat);
$("#playbyplay").children("ul").prepend(PBP.builders.html.atbat(newAtBat, true));
}
}
}
$("#pbp_play-0").remove();
};
PBP.build = function() {
PBP.feed = [];
var plays = espn.gamecast.master.plays,
outputHTML = "",
feedItems = PBP.feed,
currentPitches = [],
result = "",
isScore = false,
isResult = false,
feedItem;
for (var i = plays.length - 1; i >= 0; i--) {
if (plays[i].summaryType == "A") {
currentPitches = [];
result = "";
isScore = false;
isResult = false;
for (var x = i - 1; x >= 0; x--) {
if (plays[x].eventType == 57 && (plays[x].summaryType == "N" || plays[x].summaryType == "S") && (plays[x + 1].strikes == 3 || plays[x + 1].balls == 4 || plays[x + 1].playResult.indexOf("in play") >= 0 || plays[x + 1].playResult.toLowerCase().indexOf("en juego") >= 0)) {
isResult = true;
result = plays[x].playResult;
isScore = plays[x].isScore;
currentPitches.push(new PBP.builders.json.pitch(plays[x].id, isScore, plays[x].summaryType, plays[x].playResult + " " + plays[x].velocity, isResult));
i--;
} else {
if (plays[x].eventType == 57 && plays[x].outs == 3) {
break;
} else {
currentPitches.push(new PBP.builders.json.pitch(plays[x].id, isScore, plays[x].summaryType, plays[x].playResult + " " + plays[x].velocity, isResult));
i--;
}
}
if (isResult) {
break;
}
}
feedItems.push(new PBP.builders.json.atbat(plays[i].atbatId, plays[i].batter.firstName, plays[i].batter.lastName, plays[i].batter.id, plays[i].pitcher.firstName, plays[i].pitcher.lastName, plays[i].pitcher.id, result, currentPitches, isScore, plays[i].inningText));
} else {
feedItems.push(new PBP.builders.json.play(plays[i].id, plays[i].playResult + " " + plays[i].velocity, "", plays[i].eventType, plays[i].inningText));
}
}
var getMoreBtn = "";
if (plays.length > 0 && (plays[plays.length - 1].halfInning | 0) > 0) {
getMoreBtn = '<div id="getMore" class="getMoreBtn round-btn"><img class="more-loader" src="http://a.espncdn.com/i/gamecast/refresh/ajax-loader.gif" height="16" alt=""><span class="more-text">' + espn.gamecast.translate("Load All Plays") + "</span></div>";
}
feedItems.reverse();
for (var i = 0, n = feedItems.length; i < n; i++) {
feedItem = feedItems[i];
outputHTML += PBP.builders.html[feedItem.type](feedItem, false);
}
if (feedItems.length == 0) {
outputHTML += '<li id="pbp_play-0" class="feed-mod play"><p class="play-text">' + espn.gamecast.translate("Play-by-Play Currently Unavailable") + "</p></li>";
}
$("#playbyplay").html("<ul>" + outputHTML + "</ul>" + getMoreBtn);
$("#playbyplay").children("ul").children("li.atBat:first").addClass("expanded lastAtBat");
$title = $("#playbyplay ul li.atBat .expander");
$title.die();
$title.live("click", function(e) {
e.preventDefault();
var $this = $(this);
$this.siblings("ul.pitches").slideToggle("fast", function() {
if ($(this).is(":hidden")) {
$this.parent().removeClass("expanded");
} else {
$this.parent().addClass("expanded");
}
});
});
$("#getMore").on("click", PBP.getMore);
};
var gettingMore = false;
PBP.getMore = function() {
if (!gettingMore) {
$("#getMore").addClass("loading");
gettingMore = true;
$.ajax({
url: "/mlb/gamecast12/master?gameId=" + espn.gamecast.master.current.id + "&plays=true",
type: "GET",
dataType: "json",
success: function(data) {
espn.gamecast.master.plays = data.gamecast.plays;
PBP.build();
$("#getMore").hide();
gettingMore = false;
}
});
}
};
PBP.builders = {
html: {
atbat: function(feedItem, isExpanded) {
var title = feedItem.result != "" ? "<span class='inning'>" + feedItem.inningText + ":</span> " + feedItem.result : "<span class='inning'>" + feedItem.inningText + ":</span> " + feedItem.pitcher.firstName + " " + feedItem.pitcher.lastName + " " + espn.gamecast.translate("pitching to") + " " + feedItem.batter.firstName + " " + feedItem.batter.lastName,
outputHTML = "",
scoringClass = feedItem.isScore ? "scoring-play" : "",
expandedClass = isExpanded ? "expanded lastAtBat" : "";
outputHTML += '<li id="pbp_atbat-' + feedItem.atbatId + '" class="feed-mod play atBat ' + scoringClass + " " + expandedClass + '"><a href="#" class="expand-arrow expander"></a><p class="play-text expander"><a href="#">' + title + '</a></p><ul class="pitches">';
for (var n = 0, i = feedItem.pitches.length - 1; i >= n; i--) {
outputHTML += this.pitch(feedItem.pitches[i]);
}
outputHTML += "</ul></li>";
return outputHTML;
},
play: function(feedItem) {
if (feedItem.text != "null") {
if (feedItem.eventType == "58") {
return '<li id="pbp_play-' + feedItem.playId + '"><h2 class="inning-header">' + feedItem.text + "</h2></li>";
} else {
if (feedItem.eventType != "59" && feedItem.text.trim() != "null") {
return '<li id="pbp_play-' + feedItem.playId + '" class="feed-mod play"><p class="play-text"><span class="inning">' + feedItem.inningText + ":</span> " + feedItem.text + "</p></li>";
} else {
return "";
}
}
} else {
return "";
}
},
pitch: function(pitch) {
var outputHTML = "";
if (pitch.text.trim() != "null" && !eval(pitch.isResult) && pitch.summaryType != "A") {
outputHTML += '<li id="pbp_play-' + pitch.playId + '"><p>' + pitch.text + "</p></li>";
}
return outputHTML;
}
},
json: {
atbat: function(atbatId, batterFirstName, batterLastName, batterId, pitcherFirstName, pitcherLastName, pitcherId, result, pitches, isScore, inningText) {
this.atbatId = atbatId;
this.batter = {};
this.batter.firstName = batterFirstName;
this.batter.lastName = batterLastName;
this.batter.id = batterId;
this.pitcher = {};
this.pitcher.firstName = pitcherFirstName;
this.pitcher.lastName = pitcherLastName;
this.pitcher.id = pitcherId;
this.result = result;
this.pitches = pitches;
this.type = "atbat";
this.isScore = isScore;
this.inningText = inningText;
return this;
},
play: function(playId, text, img, eventType, inningText) {
this.playId = playId;
this.text = text;
this.img = img;
this.eventType = eventType;
this.inningText = inningText;
this.type = "play";
return this;
},
pitch: function(playId, isScore, summaryType, text, isResult) {
this.playId = playId;
this.isScore = isScore;
this.summaryType = summaryType;
this.text = text;
this.isResult = isResult;
return this;
}
}
};
PBP.feed = [];
PBP.replay = function(playId) {
if (playId !== undefined) {
var rePlayIndex = espn.gamecast.findIndex(espn.gamecast.master.plays, playId, "id"),
rePlay = rePlayIndex >= 0 ? espn.gamecast.master.plays[rePlayIndex] : undefined;
if (rePlay !== undefined) {
var resultIndex = espn.gamecast.findIndex(espn.gamecast.pbp.feed, rePlay.atbatId, "atbatId");
espn.gamecast.pbp.replayResult = resultIndex >= 0 ? espn.gamecast.pbp.feed[resultIndex].result : "";
try {
espn.gamecast.publish("replay", [{
type: rePlay.trajectory,
x: rePlay.hitXCoord,
y: rePlay.hitYCoord,
eventType: rePlay.eventType,
result: PBP.replayResult
}]);
} catch (e) {
espn.gamecast.debug("error: " + e);
}
}
}
};
PBP.handleReplayComplete = function() {
PBP.replayResult = "";
};
PBP.replayResult = "";
espn.gamecast.subscribe("replayComplete", PBP.handleReplayComplete);
})(jQuery);
espn.gamecast.scoringPlays = {};
(function($) {
var SP = espn.gamecast.scoringPlays;
SP.update = function(scoringPlay, newSP) {
if (!newSP) {
$sp = $("#sp_atbat-" + scoringPlay.playId);
$sp.replaceWith(SP.builders.html.atbat(scoringPlay, $sp.children("ul.pitches").is(":visible")));
} else {
$("#scoringPlays ul li.atBat").removeClass("expanded");
$("#scoringPlays").children("ul").prepend(SP.builders.html.atbat(scoringPlay, true));
}
$("#sp_atbat-0").remove();
};
SP.build = function() {
var sp = espn.gamecast.master.scoringPlays,
outputHTML = "";
for (var i = 0, n = sp.length; i < n; i++) {
outputHTML += SP.builders.html.atbat(sp[i], i == 0);
}
if (sp.length == 0) {
outputHTML += '<li id="sp_atbat-0" class="feed-mod play"><p>' + espn.gamecast.translate("Scoring Plays Currently Unavailable") + "</p></li>";
}
$("#scoringPlays").html("<ul>" + outputHTML + "</ul>");
$title = jQuery("#scoringPlays ul li.atBat .expander");
$title.die();
$title.live("click", function(e) {
e.preventDefault();
$this = jQuery(this);
$this.siblings("ul.pitches").slideToggle("fast", function() {
if (jQuery(this).is(":hidden")) {
$this.parent().removeClass("expanded");
} else {
$this.parent().addClass("expanded");
}
});
});
};
SP.builders = {
html: {
atbat: function(abatItem, isExpanded) {
var outputHTML = "",
expandedClass = isExpanded ? "expanded" : "",
homeTeam = espn.gamecast.master.current.home,
awayTeam = espn.gamecast.master.current.away,
homeText = abatItem.inningText.indexOf("Bot") >= 0 || abatItem.inningText.indexOf("Baja") >= 0 ? "<span>" + homeTeam.abbrev.toUpperCase() + " " + abatItem.homeScore + "</span>" : homeTeam.abbrev.toUpperCase() + " " + abatItem.homeScore,
awayText = abatItem.inningText.indexOf("Top") >= 0 || abatItem.inningText.indexOf("Alta") >= 0 ? "<span>" + awayTeam.abbrev.toUpperCase() + " " + abatItem.awayScore + "</span>" : awayTeam.abbrev.toUpperCase() + " " + abatItem.awayScore;
outputHTML += '<li id="sp_atbat-' + abatItem.playId + '" class="feed-mod play atBat scoring-play ' + expandedClass + '"><div class="score-line"><h2 class="inning">' + abatItem.inningText + '</h2><h2 class="score">' + awayText + " - " + homeText + '</h2></div><a href="#" class="expand-arrow expander"></a><p class="play-text expander"><a href="#">' + abatItem.playResult + '</a></p><ul class="pitches">';
for (var i = 0, n = abatItem.pitches.length; i < n; i++) {
outputHTML += this.pitch(abatItem.pitches[i]);
}
outputHTML += "</ul></li>";
return outputHTML;
},
pitch: function(pitch) {
var outputHTML = '<li id="sp_play-' + pitch.playId + '"><p>' + pitch.pitchResult + "</p></li>";
return outputHTML;
}
}
};
SP.replay = function(playId) {
if (playId !== undefined) {
var rePlayIndex = espn.gamecast.findIndex(espn.gamecast.master.plays, playId, "id"),
rePlay = rePlayIndex >= 0 ? espn.gamecast.master.plays[rePlayIndex] : undefined;
if (rePlay !== undefined) {
var resultIndex = espn.gamecast.findIndex(espn.gamecast.activityFeed.feed, rePlay.atbatId, "atbatId");
espn.gamecast.scoringPlays.replayResult = resultIndex >= 0 ? espn.gamecast.activityFeed.feed[resultIndex].result : "";
try {
espn.gamecast.publish("replay", [{
type: rePlay.trajectory,
x: rePlay.hitXCoord,
y: rePlay.hitYCoord,
eventType: rePlay.eventType,
result: SP.replayResult
}]);
} catch (e) {
espn.gamecast.debug("error: " + e);
}
}
}
};
SP.handleReplayComplete = function() {
SP.replayResult = "";
};
SP.replayResult = "";
espn.gamecast.subscribe("replayComplete", SP.handleReplayComplete);
})(jQuery);
espn.gamecast.socialLinks = {};
(function($) {
var SOC = espn.gamecast.socialLinks,
bitlyURL = "nZqH26";
SOC.build = function(current) {
var outputHTML = '<div class="buttons">' + SOC.buildFacebook(current) + SOC.buildTwitter(current) + "</div>" + SOC.buildBugReport();
$("#socialLinks-wrap").html(outputHTML);
SOC.activateTwitterLink();
SOC.activateFacebookLink(current.id);
};
SOC.buildMobile = function(current) {
$("#mobile-share-container").html(SOC.buildFacebook(current) + SOC.buildTwitter(current));
SOC.activateFacebookLink(current.id);
SOC.activateTwitterLink();
};
SOC.buildTwitter = function(current) {
var scoreText = current.home.score > current.away.score ? "#" + current.home.abbrev.toUpperCase() + " " + current.home.score + " vs #" + current.away.abbrev.toUpperCase() + " " + current.away.score : "#" + current.away.abbrev.toUpperCase() + " " + current.away.score + " at #" + current.home.abbrev.toUpperCase() + " " + current.home.score,
midInn = settings.lang == "es" ? current.status1.indexOf("Mitad") : current.status1.indexOf("Mid"),
gameStatus = "";
if (current.statusId == 3) {
gameStatus = "F";
} else {
if (midInn) {
gameStatus = "Mid " + current.inning;
} else {
gameStatus = (parseInt(current.halfInning, 10) % 2 === 0 ? "Top " : "Bot ") + current.inning;
}
}
return '<div style="float: right;"><a id="twitter_link" class="twitter_link" href="http://twitter.com/share" data-url="http://espn.go.com/mlb/gamecast?gameId=' + current.id + '" display-url="http://espn.go.com/mlb/gamecast?gameId=' + current.id + '" data-text="Follow live on ESPN MLB Gamecast ' + scoreText + " " + gameStatus + ' #espn #mlb #gamecast"><span class="birdy"></span><span class="text">Tweet</span></a></div>';
};
SOC.buildFacebook = function(current) {
return '<div style="float: left; padding-right: 10px; padding-top: 1px;"><a id="facebook_link" name="fb_share" type="button" target="_blank" share_url="http://scores.espn.go.com/mlb/gamecast?gameId=' + current.id + '" href="http://www.facebook.com/sharer.php"><img src="http://a.espncdn.com/i/gamecast/fb-share.png" width="60" height="18" /></a></div>';
};
SOC.buildOptOut = function() {
if (settings.lang == "en") {
return '<div class="bug-container" style="text-align:center"><a id="opt-out" href="#exit-beta">' + espn.gamecast.translate("Exit BETA Version") + "</a></div>";
} else {
return "";
}
};
SOC.activateTwitterLink = function() {
$("#twitter_link").off().on("click", function(e) {
var $this = $(this);
e.preventDefault();
window.open("https://twitter.com/intent/tweet?text=" + encodeURIComponent($this.attr("data-text")) + "&url=" + encodeURIComponent($this.attr("data-url")), "twittersharer", "width=550,height=275,scrollbars=0");
});
};
SOC.activateFacebookLink = function(currentId) {
$("#facebook_link").off().on("click", function(e) {
e.preventDefault();
window.open("http://www.facebook.com/sharer.php?u=http://scores.espn.go.com/" + settings.sport.toLowerCase() + "/gamecast?gameId=" + currentId, "facebooksharer", "width=550,height=275,scrollbars=0");
});
};
SOC.popFeedBack = function() {
var gameInfoStr = "";
var d = new Date();
gameInfoStr = "&Original: " + settings.gameId + " Current: " + espn.gamecast.master.current.id;
gameInfoStr += "+<br /><b>Resolution:</b>+" + screen.width + "x" + screen.height + "+(" + screen.availWidth + "x" + screen.availHeight + ")";
window.open("http://dynamic.espn.go.com/espn/bugs?url=http://scores.espn.go.com/" + settings.sport + "/gamecast (" + (d.getMonth() + 1) + "-" + d.getDate() + "-" + d.getFullYear() + ")" + gameInfoStr, "Bugs", "nonresizable,noscrollbars,height=400,width=400");
};
SOC.buildBugReport = function() {
if (settings.lang != "es") {
return '<div class="bug-container"><a href="#" onclick="espn.gamecast.socialLinks.popFeedBack(); return false;">Send us your Feedback</a></div>';
} else {
return "";
}
};
})(jQuery);
espn.gamecast.video = {};
(function($) {
var VID = espn.gamecast.video,
log = espn.gamecast.debug,
flashVersion = swfobject.getFlashPlayerVersion(),
showVideoAd = true,
playingVideoAd = false,
waitedForAd = true,
playingHighlight = false,
isIpad = /iPad/i.test(navigator.userAgent),
hasFlash = false,
hasVideoPlayer = false,
lastMediaId = 0,
adsViewable = true,
adTimer, countdownInterval, videoAdURL = "Pre-Roll",
isPreroll = true,
isMobile = window.location.search.indexOf("version=mobile") >= 0,
allowNativePlayer = espn.gamecast.checkHTML5Player();
VID.embedPlayer = function() {
if (allowNativePlayer) {
hasVideoPlayer = true;
var playerType = settings.lang == "es" ? "deportes" : "espn";
if (lastMediaId == 0) {
espn.video.embed({
player: "gameCast09",
width: 576,
height: 324,
cms: playerType
});
} else {
espn.video.embed({
player: "gameCast09",
width: 576,
height: 324,
id: lastMediaId,
cms: playerType
});
}
espn.gamecast.debug("playerType = " + playerType);
}
};
VID.getDebugInfo = function() {
espn.gamecast.debug("Show Video Ad: " + showVideoAd + ", Playing Video Ad: " + playingVideoAd + ", Waited for Ad: " + waitedForAd);
};
VID.totallyWaited = function() {
waitedForAd = true;
};
VID.bringItAroundTown = function(val) {
waitedForAd = val === true;
showVideoAd = val === true;
};
VID.playAd = function() {
if (!isMobile && !playingVideoAd && adsViewable && showVideoAd && waitedForAd) {
espn.gamecast.debug("Play ad");
espn.gamecast.publish("comPlayer", [true, false, false]);
var adVars = {
adUnit: videoAdURL,
midSequence: 0,
siteSection: "espn:gamecast:" + settings.sport.toLowerCase(),
videoID: "espn:gamecast:" + settings.sport.toLowerCase()
};
espn.video.insertAd(adVars);
playingVideoAd = true;
waitedForAd = false;
VID.setAdTimer();
} else {
espn.gamecast.debug("Not playing ad");
}
};
VID.preventAds = function() {
adsViewable = false;
};
VID.allowAds = function() {
adsViewable = true;
};
VID.clearAdTimer = function() {
clearTimeout(adTimer);
adTimer = undefined;
waitedForAd = false;
showVideoAd = false;
log("Ad Timer: " + adTimer);
};
VID.setAdTimer = function() {
adTimer = setTimeout(function() {
waitedForAd = true;
showVideoAd = true;
}, 300000);
};
VID.getAdTimer = function() {
return adTimer;
};
VID.skipAd = function(skip) {
if (playingVideoAd) {
if (!isPreroll) {
espn.gamecast.publish("bannerAdRefresh");
}
if (skip !== undefined && skip == "yes") {
espn.gamecast.track("link", {
info: "videoadskip"
});
espn.video.skipAd();
}
playingVideoAd = false;
espn.gamecast.publish("comPlayer", [false, false, true]);
} else {
if (skip == "yes") {
espn.gamecast.publish("comPlayer", [false, false, true]);
}
}
};
function onAdStart(duration) {
if (!isNaN(duration)) {
countdown(parseInt(duration, 10));
} else {
document.getElementById("note").innerHTML = "Advertisement: Content will continue after ad is complete";
}
isPreroll = false;
}
function countdown(duration) {
clearInterval(countdownInterval);
var start = duration;
var secondString = settings.lang == "es" ? " segundos" : " seconds";
if (start == 1) {
secondString = settings.lang == "es" ? " segundo" : " second";
}
document.getElementById("countdown").innerHTML = start + secondString;
countdownInterval = setInterval(function() {
start--;
secondString = settings.lang == "es" ? " segundos" : " seconds";
if (start == 1) {
secondString = settings.lang == "es" ? " segundo" : " second";
}
document.getElementById("countdown").innerHTML = start + secondString;
if (start <= 0) {
setTimeout(function() {
jQuery.pub("espn.video.ad.end");
}, 5000);
clearInterval(countdownInterval);
}
}, 1000);
}
VID.cancelCountdown = function() {
clearInterval(countdownInterval);
};
VID.update = function(video, newVideo) {
var videoHTML = VID.builders.html(video);
if (!newVideo) {
$vid = $("#vid-" + video.id);
$vid.replaceWith(videoHTML);
} else {
$("#videoFeed").children("ul").prepend(videoHTML);
}
$("#vid-0").remove();
};
VID.build = function(videos) {
var outputHTML = "";
if (videos !== undefined) {
for (var i = 0, n = videos.length; i < n; i++) {
if (espn.gamecast.isVideoViewable(videos[i])) {
outputHTML += VID.builders.html(videos[i]);
}
}
if (videos.length == 0 || outputHTML == "") {
outputHTML = "<li id='vid-0' class='feed-mod photo video'><p>" + espn.gamecast.translate("Videos Currently Unavailable") + "</p></li>";
}
}
$("#videoFeed").html("<ul>" + outputHTML + "</ul>");
};
VID.builders = {
html: function(video) {
var vidInfo = "";
if (video.playId == undefined || video.playId <= 0) {
vidInfo = '<p class="vid-descrip"><a href="#" class="video-highlight" data-videoId="' + video.id + '">' + video.title + '</a></p><p class="vid-date">' + video.description + " (" + video.length.substring(3) + ")</p>";
} else {
vidInfo = '<p class="playText"><a href="#" class="video-highlight" data-videoId="' + video.id + '"><span>' + video.downDistance + "</span>" + video.playText + "</a> (" + video.length.substring(3) + ")</p>";
}
return '<li id="vid-' + video.id + '" class="feed-mod video" abbr="' + video.playId + '"><div class="video-container"><div class="vid-icon"></div><a href="#" class="video-highlight" data-videoId="' + video.id + '"><img class="thumb" src="' + video.thumbnail + '" onerror="this.src=\'http://a.espncdn.com/i/gamecast/football/vid_thumb_default.png\'; return false;"></a></div>' + vidInfo + '<div class="clear"></div></li>';
}
};
VID.playHighlight = function(mediaId) {
lastMediaId = mediaId;
allowNativePlayer = espn.gamecast.checkHTML5Player();
if (!playingVideoAd) {
if (hasFlash || allowNativePlayer) {
espn.gamecast.publish("comPlayer", [true, true, false]);
document.getElementById("note").style.display = "none";
document.getElementById("closeButton").style.display = "block";
if (hasVideoPlayer) {
espn.video.play(mediaId);
playingHighlight = true;
} else {
VID.embedPlayer();
}
}
}
};
VID.stopHighlight = function() {
if (playingHighlight) {
espn.video.pause();
}
playingHighlight = false;
playingVideoAd = false;
$("#note").show();
$("#closeButton").hide();
espn.gamecast.publish("comPlayer", [false, true, false]);
return false;
};
if (flashVersion !== undefined && flashVersion.major !== undefined && flashVersion.major >= 10 && !isMobile) {
$("#video-frame").removeClass("vidHide");
hasFlash = true;
VID.embedPlayer();
} else {
if (!isMobile) {
setTimeout(function() {
espn.gamecast.publish("comPlayer", [false, false, true]);
}, 1000);
}
}
$("#video-frame").on("click", "#closeButton", function(e) {
e.preventDefault();
VID.stopHighlight();
});
espn.video.subscribe("espn.video.init", VID.playAd);
espn.video.subscribe("espn.video.ad.end", VID.skipAd);
espn.video.subscribe("espn.video.ad.start", onAdStart);
espn.video.subscribe("espn.video.playlist.ended", VID.stopHighlight);
})(jQuery);
espn.gamecast.audio = {};
(function($) {
var AUD = espn.gamecast.audio;
AUD.startVolume = 1;
AUD.startMute = false;
AUD.preLoaded = false;
AUD.initFlashApi = function(playerId) {
espn.gamecast.audio.radioPlayer = document.getElementById(playerId);
};
AUD.loadLive = function(streamUrl, autoPlay) {
if (streamUrl) {
streamUrl = streamUrl.replace("token=", "primaryToken=");
var parameters = {
streamProtocol: "akamai",
src: streamUrl,
plugin_OSMFHLS: "http://a.espncdn.com/i/espnradio/11/player/swf/plugins/OSMFHLSPlugin.swf",
plugin_MediaAnalytics: "http://79423.analytics.edgesuite.net/csma/plugin/csma.swf",
streamType: "live",
autoPlay: autoPlay,
bufferTime: "10",
width: "1",
height: "1",
volume: espn.gamecast.audio.startVolume,
muted: espn.gamecast.audio.startMute,
verbose: false,
controlBarAutoHide: true,
javascriptCallbackFunction: "espn.gamecast.audio.initFlashApi",
csmaPluginPath: "http://79423.analytics.edgesuite.net/csma/plugin/csma.swf",
csmaBeaconPath: "http://ma123-c.analytics.edgesuite.net/config/beacon-1355.xml"
};
swfobject.embedSWF(espn.core.cdnHTTPPath + "i/espnradio/11/player/swf/stable/EspnRadioPlayer.Live.swf", "audio-player-container", 1, 1, "10.1.0", {}, parameters, {
allowFullScreen: "false",
wmode: "transparent",
allowscriptaccess: "always"
}, {
name: "audio-player-container"
});
}
};
AUD.buildStations = function(stations) {
if (stations) {
if (stations.length > 0) {
$("#live-audio").empty();
for (var i = 0; i < stations.length; i++) {
nowPlaying = stations[i].nowPlaying;
streamInfo = stations[i].streamInfo;
if ((typeof nowPlaying !== "undefined") && (typeof streamInfo !== "undefined")) {
stationName = nowPlaying.stationName;
showName = nowPlaying.showName;
thumb = nowPlaying.showImage_300;
streamUrl = streamInfo.streamUrl;
$("#live-audio").append("<div class=\"feed-mod video audio-item {type:'live',streamUrl:'" + streamUrl + "',thumb:'" + thumb + '\'}"><p class="vid-descrip"><a href="#" class="audio-play">' + stationName + '</a></p><p class="vid-date">' + showName + ' <img src="' + espn.core.cdnHTTPPath + 'icons/live.gif"></p></div>');
if (i == 0 && !espn.gamecast.audio.preLoaded) {
espn.gamecast.audio.updateNowPlaying(stationName, showName, thumb);
espn.gamecast.audio.loadLive(streamUrl, false);
espn.gamecast.audio.preLoaded = true;
$("#live-audio .audio-item:first").addClass("active");
}
}
}
}
}
};
AUD.buildPodcasts = function(podcasts) {
if (podcasts) {
if (podcasts.length > 0) {
$("#ondemand-audio").empty();
for (var i = 0; i < podcasts.length; i++) {
name = podcasts[i].name;
shortDescription = podcasts[i].shortDescription;
enclosureUrl = podcasts[i].enclosureUrl;
if (podcasts[i].images) {
thumb = podcasts[i].images.image134;
}
$("#ondemand-audio").append("<div class=\"feed-mod video audio-item {type:'ondemand',url:'" + enclosureUrl + "',thumb:'" + thumb + '\'}"><p class="vid-descrip"><a href="#" class="audio-play">' + name + '</a></p><p class="vid-date">' + shortDescription + "</p></div>");
if (i == 0 && !espn.gamecast.audio.preLoaded) {
espn.gamecast.audio.updateNowPlaying(name, shortDescription, thumb);
espn.gamecast.audio.loadOnDemand(enclosureUrl, false);
espn.gamecast.audio.preLoaded = true;
$("#ondemand-audio .audio-item:first").addClass("active");
}
}
}
}
};
AUD.loadOnDemand = function(fileUrl, autoPlay) {
var parameters = {
src: fileUrl,
plugin_AkamaiAdvancedStreamingPlugin: "http://players.edgesuite.net/flash/plugins/osmf/advanced-streaming-plugin/fp10.1/v1.2/AkamaiAdvancedStreamingPlugin.swf",
plugin_MediaAnalytics: "http://79423.analytics.edgesuite.net/csma/plugin/csma.swf",
streamType: "recorded",
autoPlay: autoPlay,
bufferTime: 10,
volume: espn.gamecast.audio.startVolume,
muted: espn.gamecast.audio.startMute,
width: "1",
height: "1",
verbose: false,
controlBarAutoHide: true,
javascriptCallbackFunction: "espn.gamecast.audio.initFlashApi",
csmaPluginPath: "http://79423.analytics.edgesuite.net/csma/plugin/csma.swf",
csmaBeaconPath: "http://ma123-c.analytics.edgesuite.net/config/beacon-1355.xml"
};
swfobject.embedSWF(espn.core.cdnHTTPPath + "i/espnradio/11/player/swf/stable/EspnRadioPlayer.OnDemand.swf", "audio-player-container", 1, 1, "10.1.0", {}, parameters, {
allowFullScreen: "false",
wmode: "transparent",
allowscriptaccess: "always"
}, {
name: "audio-player-container"
});
};
AUD.updateNowPlaying = function(title, description, thumb) {
$("#audio-title").html(title);
$("#audio-description").html(description);
$("#audio-thumb").attr("src", thumb).show();
};
AUD.build = function() {
var flashVersion = swfobject.getFlashPlayerVersion();
if ((flashVersion.major == 10 && flashVersion.minor >= 1) || flashVersion.major > 10) {
$.ajax({
url: "/espnradio/feeds/gamecast.json",
data: {
sport: settings.sport
},
dataType: "json",
success: function(json) {
if (json) {
$("#audio-loading").hide();
$("#now-playing").show().siblings("h2.period-header").show();
$("div.audio-item").live("click", function(e) {
var $this = $(this);
var metadata = $this.metadata();
var description = $this.find("p.vid-date").text();
var title = $this.find("a.audio-play").text();
if (metadata.type == "live" || metadata.type == "ondemand") {
if (metadata.type == "live") {
espn.gamecast.audio.loadLive(metadata.streamUrl, true);
} else {
espn.gamecast.audio.loadOnDemand(metadata.url, true);
}
$("#radioTab .audio-item").removeClass("active");
$this.addClass("active");
$("#play-pause-btn").attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/pause.png");
espn.gamecast.audio.updateNowPlaying(title, description, metadata.thumb);
}
e.preventDefault();
});
$("#play-pause-btn").live("click mouseover mouseout", function(event) {
if (espn.gamecast.audio.radioPlayer) {
if (event.type == "click") {
espn.gamecast.audio.togglePlayPause();
} else {
if (event.type == "mouseover") {
if (espn.gamecast.audio.isPlaying()) {
$(this).attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/pause_hover.png");
} else {
$(this).attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/play_hover.png");
}
} else {
if (event.type == "mouseout") {
if (espn.gamecast.audio.isPlaying()) {
$(this).attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/pause.png");
} else {
$(this).attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/play.png");
}
}
}
}
}
});
$("#mute-btn").live("click", function(event) {
espn.gamecast.audio.toggleMute();
});
$("#vol-slider").slider({
range: "min",
min: 0,
max: 100,
value: 100,
change: function(event, ui) {
var newVolume = ui.value / 100;
espn.gamecast.audio.setVolume(newVolume);
}
});
if ((typeof(json.stations) == "object" && json.stations.length > 0) || (typeof(json.podcasts) == "object" && json.podcasts.length > 0)) {
if (typeof(json.stations) == "object" && json.stations.length > 0) {
espn.gamecast.audio.buildStations(json.stations);
}
if (typeof(json.podcasts) == "object" && json.podcasts.length > 0) {
espn.gamecast.audio.buildPodcasts(json.podcasts);
}
} else {
$("#radioTab").html("<p>Sorry, no audio available at this time.</p>");
}
}
},
error: function() {
$("#radioTab").html("<p>Sorry, no audio available at this time.</p>");
}
});
} else {
$("#radioTab").html('<p>Sorry, you do not have the correct version of Flash installed. Flash version 10.1 or later is required. <a href="http://get.adobe.com/flashplayer/">Get Flash Now.</a></p>');
}
espn.gamecast.gotAudio = true;
};
AUD.isPlaying = function() {
if (espn.gamecast.audio.radioPlayer) {
return espn.gamecast.audio.radioPlayer.getPlaying();
} else {
return false;
}
};
AUD.playAudio = function() {
if (espn.gamecast.audio.radioPlayer) {
espn.gamecast.audio.radioPlayer.play2();
$("#play-pause-btn").attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/pause.png");
}
};
AUD.pauseAudio = function() {
if (espn.gamecast.audio.radioPlayer) {
espn.gamecast.audio.radioPlayer.pause();
$("#play-pause-btn").attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/player/skin/images/play.png");
}
};
AUD.togglePlayPause = function() {
if (espn.gamecast.audio.isPlaying()) {
espn.gamecast.audio.pauseAudio();
} else {
espn.gamecast.audio.playAudio();
}
};
AUD.isMuted = function() {
if (espn.gamecast.audio.radioPlayer) {
return espn.gamecast.audio.radioPlayer.getMuted();
} else {
return espn.gamecast.audio.startMute;
}
};
AUD.muteAudio = function() {
if (espn.gamecast.audio.radioPlayer) {
espn.gamecast.audio.radioPlayer.setMuted(true);
}
espn.gamecast.audio.startMute = true;
$("#mute-btn").attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/gamecast/nfl/icon_sound_mute.png");
};
AUD.unMuteAudio = function() {
if (espn.gamecast.audio.radioPlayer) {
espn.gamecast.audio.radioPlayer.setMuted(false);
}
espn.gamecast.audio.startMute = false;
$("#mute-btn").attr("src", espn.core.cdnHTTPPath + "i/espnradio/11/gamecast/nfl/icon_sound.png");
};
AUD.toggleMute = function() {
if (espn.gamecast.audio.isMuted() || espn.gamecast.audio.startMute) {
espn.gamecast.audio.unMuteAudio();
} else {
espn.gamecast.audio.muteAudio();
}
};
AUD.setVolume = function(volume) {
if (espn.gamecast.audio.radioPlayer) {
espn.gamecast.audio.radioPlayer.setVolume(volume);
}
espn.gamecast.audio.startVolume = volume;
};
})(jQuery);
espn.gamecast.twitterFeed = {};
(function($) {
TWIT = espn.gamecast.twitterFeed;
var timeUpdaterInterval = 30000,
timeUpdater;
TWIT.update = function(tweet, isNew) {
if (tweet !== undefined) {
if (isNew) {
$("#twitterFeed").children("ul").prepend(TWIT.builders.html(tweet));
} else {
$("#tweet-" + tweet.tweetId).replaceWith(TWIT.builders.html(tweet));
}
}
$("#tweet-0").hide();
};
TWIT.build = function(tweets) {
var outputHTML = "";
tweets.sort(function(a, b) {
return b.timeStamp - a.timeStamp;
});
if (tweets != undefined && tweets.length > 0) {
for (var i = 0, n = tweets.length; i < n; i++) {
outputHTML += TWIT.builders.html(tweets[i]);
}
$("#tweet-0").hide();
} else {
outputHTML = '<li id="tweet-0"><p>' + espn.gamecast.translate("Tweets Currently Unavailable") + "</p></li>";
}
var filterHTML = "";
if (settings.lang == "en") {
filterHTML = TWIT.getFilterHTML();
}
$("#twitterFeed").html(filterHTML + "<ul>" + outputHTML + "</ul>");
TWIT.bindFilter();
timeUpdater = setTimeout(TWIT.timestampUpdate, timeUpdaterInterval);
};
TWIT.timestampUpdate = function() {
timeUpdater = clearTimeout(timeUpdater);
$(".timestamp-updater").each(function(i) {
var $this = $(this),
ts = $this.attr("data-timestamp");
$this.html(TWIT.getTimeSince(parseInt(ts, 10)));
});
timeUpdater = setTimeout(TWIT.timestampUpdate, timeUpdaterInterval);
};
TWIT.builders = {
html: function(tweet) {
if (tweet !== undefined) {
var userName = eval(tweet.isRetweet) ? tweet.original.userName : tweet.userName,
displayName = eval(tweet.isRetweet) ? tweet.original.displayName : tweet.displayName,
img = eval(tweet.isRetweet) ? tweet.original.img : tweet.img;
return '<li id="tweet-' + tweet.tweetId + '" class="feed-mod tweet ' + (tweet.isESPNTalent ? "espner" : "") + '">' + (eval(tweet.isRetweet) ? '<div class="retweet-note"><img src="http://a.espncdn.com/i/gamecast/twitter/retweet.png" /><a href="https://twitter.com/' + tweet.userName + '" target="_blank">' + tweet.displayName + "</a> retweeted</div>" : "") + '<div class="twit-pic"><a href="https://twitter.com/' + userName + '" target="_blank"><img src="' + img + '" width="48" height="48" border="0" title="' + userName + '" alt="' + userName + '" class="post-img" /></a></div><div class="twit-content"><div class="twit-header"><span class="twit-time"><a href="https://twitter.com/' + userName + "/status/" + tweet.tweetId + '" class="timestamp-updater" data-timestamp="' + tweet.timeStamp + '" target="_blank">' + TWIT.getTimeSince(tweet.timeStamp) + '</a></span><a href="https://twitter.com/" target="_blank"><img src="http://a.espncdn.com/i/gamecast/twitter/twitter-logo.png" class="twitter-logo" /></a><span class="twit-name"><a href="https://twitter.com/' + userName + '" target="_blank">' + displayName + '</a></span><span class="twit-handle">@<a href="https://twitter.com/' + userName + '" target="_blank">' + userName + '</a></span></div><p class="twit-text">' + TWIT.linkitup(tweet.text.replace(/&amp;#|&#x26;#/g, "&#")) + '</p><div class="twit-footer">' + TWIT.getTwitterLinks(tweet) + '</div></div><div class="clear"></div></li>';
} else {
return "";
}
}
};
TWIT.getTwitterLinks = function(tweet) {
var linkHTML = '<ul class="twit-actions">',
actions = [{
link: "https://twitter.com/intent/tweet?in_reply_to=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/reply.png",
text: "Reply",
imgClass: ""
}, {
link: "https://twitter.com/intent/retweet?tweet_id=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/retweet.png",
text: "Retweet",
imgClass: "retweet"
}, {
link: "https://twitter.com/intent/favorite?tweet_id=" + tweet.tweetId,
img: "http://a.espncdn.com/i/gamecast/twitter/fav.png",
text: "Favorite",
imgClass: ""
}];
for (var i = 0, n = actions.length; i < n; i++) {
linkHTML += '<li class="twit-action">';
linkHTML += '<a href="' + actions[i].link + '" target="_blank"><img src="' + actions[i].img + '" class="' + actions[i].imgClass + '"/> ' + actions[i].text + "</a>";
linkHTML += "</li>";
}
linkHTML += "</ul>";
return linkHTML;
};
TWIT.linkitup = function(text) {
var returnText = text;
returnText = returnText.replace(/@(\w*(?!<))/g, function(m1, m2) {
return ' @<a href="https://twitter.com/' + m2.trim() + '" target="_blank">' + m2.trim() + "</a> ";
});
returnText = returnText.replace(/((^|\s)\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function(m1) {
return ' <a href="' + m1.trim() + '" target="_blank">' + m1.trim() + "</a> ";
});
returnText = returnText.replace(/(^|\s)#(\w*(?!<))/g, function(m1, m2, m3) {
return ' #<a href="https://twitter.com/search?q=%23' + m3.trim() + '&src=hash" target="_blank">' + m3.trim() + "</a> ";
});
return returnText;
};
TWIT.getFilterHTML = function() {
var out = '<div class="twitter-filter"><a id="toggle-espn-tweets" class="round-btn round-btn-small">ONLY ESPN TWEETS - OFF</a></div>';
return out;
};
TWIT.bindFilter = function() {
$("#toggle-espn-tweets").on("click", function(e) {
var $this = $(this);
if (!$this.hasClass("on")) {
$("#twitterFeed").children("ul").addClass("espn-only");
$this.addClass("on").text("ONLY ESPN TWEETS - ON");
} else {
$("#twitterFeed").children("ul").removeClass("espn-only");
$this.removeClass("on").text("ONLY ESPN TWEETS - OFF");
}
});
};
TWIT.bindTweetLinks = function() {
if (espn.gamecast.isMobile) {
$("#twitterFeed ul").off().on("click", "a", function(e) {
var $this = $(this);
e.preventDefault();
window.open($this.attr("href"), "twittersharer", "scrollbars=0");
});
}
};
TWIT.getTimeSince = function(timeStr) {
var date = new Date((parseInt(timeStr, 10) || "")),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) {
return "";
}
return day_diff == 0 && (diff < 3600 && Math.floor(diff / 60) + "m" || diff < 86400 && Math.floor(diff / 3600) + " h") || day_diff < 7 && day_diff + "d" || day_diff < 31 && Math.ceil(day_diff / 7) + "w";
};
})(jQuery);
espn.gamecast.photos = {};
(function($) {
PHOTO = espn.gamecast.photos;
PHOTO.update = function(photo, isNewPhoto) {
if (!isNewPhoto) {
$photo = $("#photo-" + photo.photoId);
$photo.replaceWith(PHOTO.builders.html(photo));
} else {
setTimeout(function() {
$("#photoFeed").children("ul").prepend(PHOTO.builders.html(photo));
}, 10000);
}
if (photo.photoId != 0) {
$("#photo-0").hide();
}
};
PHOTO.build = function(photos) {
var params = {},
setParams = location.search.replace(/([^?=&]+)(=([^&#]*))?/g, function($0, $1, $2, $3) {
params[$1] = $3;
}),
outputHTML = "";
if (photos != undefined && photos.length > 0) {
var photoLimit = photos.length > 50 && params.appsrc && params.appsrc === "sc" ? 50 : photos.length;
for (var i = 0; i < photoLimit; i++) {
outputHTML += PHOTO.builders.html(photos[i]);
}
$("#photo-0").hide();
} else {
outputHTML = '<li id="photo-0" class="feed-mod photo video"><p>' + espn.gamecast.translate("Photos Currently Unavailable") + "</p></li>";
}
$("#photoFeed").html("<ul>" + outputHTML + "</ul>");
};
PHOTO.builders = {
html: function(photo) {
var displayText = photo.text.length > 250 ? photo.text.substring(0, photo.text.indexOf(" ", 230)) + "..." : photo.text;
return '<li id="photo-' + photo.photoId + '" class="feed-mod photo video"><a href="#" class="launchGallery"><img width="110" src="' + photo.img + '" title="' + photo.text + '" onerror="this.src=\'http://a.espncdn.com/combiner/i?img=broadband/video/images/thumb_default_576.gif&w=110\'" /></a><p class="vid-date">' + displayText + "</p></li>";
}
};
})(jQuery);
espn.gamecast.photoGallery = {};
(function($) {
var PG = espn.gamecast.photoGallery,
photos = espn.gamecast.master.photos,
current = espn.gamecast.master.current,
currentPhotoIndex = 0,
isMobile;
PG.update = function(photo, newPhoto) {
if ($("#photoContainer").length > 0 && newPhoto) {
$("#thumbnail-wrap").children().children("ul").append(PG.buildThumbHTML(photo, ""));
}
};
PG.init = function() {
isMobile = espn.gamecast.isMobile;
var $activityGalleryLinks = $("#activityFeed").find("a.launchGallery");
$activityGalleryLinks.die();
$activityGalleryLinks.live("click", espn.gamecast.photoGallery.loadGallery);
var $photoFeedGalleryLinks = $("#photoFeed").find("a.launchGallery");
$photoFeedGalleryLinks.die();
$photoFeedGalleryLinks.live("click", espn.gamecast.photoGallery.loadGallery);
};
PG.loadGallery = function(e) {
var $this = $(this);
firstPhotoId = $this.parent()[0].id.split("-")[1];
e.preventDefault();
if (firstPhotoId != undefined) {
if (isMobile) {
window.location = PG.getGalleryUrl(firstPhotoId);
} else {
espn.gamecast.publish("hideWatch");
$("body").prepend(PG.getGalleryHTML(firstPhotoId));
espn.gamecast.track("link", {
info: "galleryLoaded"
});
$("#photo-close").bind("click", espn.gamecast.photoGallery.closeGallery);
$("#photo-prevArrow").bind("click", espn.gamecast.photoGallery.loadPrev);
$("#photo-nextArrow").bind("click", espn.gamecast.photoGallery.loadNext);
$("#thumbnail-wrap").children().children("ul").children(".thumbnail").bind("click", espn.gamecast.photoGallery.loadThumb);
$("#thumbnail-header").bind("click", espn.gamecast.photoGallery.toggleThumbs);
}
} else {
alert("Please try a different Photo");
}
};
PG.getGalleryUrl = function(photoId) {
return "http://m.espn.go.com/" + settings.sport + "/slideshow?gameId=" + current.id + (photoId ? "&photoItemId=" + photoId : "");
};
PG.toggleThumbs = function() {
var $header = $(this),
$wrap = $("#thumbnail-wrap");
if ($wrap.css("height") == "0px") {
$wrap.animate({
height: "200px"
}, 750, function() {
$header.children(".button").removeClass("open").addClass("close");
});
} else {
$wrap.animate({
height: "0px"
}, 750, function() {
$header.children(".button").removeClass("close").addClass("open");
});
}
};
PG.closeGallery = function(e) {
e.preventDefault();
$("#photoContainer").fadeOut(500, function() {
$(this).remove();
espn.gamecast.publish("showWatch");
});
};
PG.loadPrev = function() {
var nextIndex = currentPhotoIndex == 0 ? espn.gamecast.master.photos.length - 1 : currentPhotoIndex - 1;
PG.loadPhoto(nextIndex);
};
PG.loadNext = function() {
var nextIndex = currentPhotoIndex == espn.gamecast.master.photos.length - 1 ? 0 : currentPhotoIndex + 1;
PG.loadPhoto(nextIndex);
};
PG.loadThumb = function() {
PG.loadPhoto(espn.gamecast.findIndex(espn.gamecast.master.photos, this.id.split("-")[1], "photoId"));
};
PG.loadPhoto = function(newIndex) {
var thisPhoto = espn.gamecast.master.photos[newIndex],
photoCaption = thisPhoto.text.indexOf("(Photo") > 0 ? thisPhoto.text.substring(0, thisPhoto.text.indexOf("(Photo")) : thisPhoto.text.substring(0, thisPhoto.text.indexOf("(AP")),
photoCredit = thisPhoto.text.indexOf("(Photo") > 0 ? thisPhoto.text.substring(thisPhoto.text.indexOf("(Photo")) : thisPhoto.text.substring(thisPhoto.text.indexOf("(AP")),
numPhotos = espn.gamecast.master.photos.length;
$("#photoWindow").fadeOut(500, function() {
var $this = $(this);
$this.html('<img src="' + thisPhoto.largeImg + '" oncontextmenu="return false;" />');
$this.children("img").load(function() {
$this.fadeIn();
});
$("#thumbnail-wrap").find("li.thumbnail").removeClass("current");
$("#thumbnail-" + thisPhoto.photoId).addClass("current");
$("#photo-caption").html(photoCaption);
$("#photo-credit").html(photoCredit);
$("#photo-counter").html((newIndex + 1) + " of " + numPhotos);
currentPhotoIndex = newIndex;
});
espn.gamecast.track("link", {
info: "photoLoaded"
});
};
PG.getGalleryHTML = function(photoId) {
currentPhotoIndex = espn.gamecast.findIndex(espn.gamecast.master.photos, photoId, "photoId");
var photos = espn.gamecast.master.photos,
thumbnailClass, numPhotos = photos.length,
thisPhoto = photos[currentPhotoIndex],
photoCaption = thisPhoto.text.indexOf("(Photo") > 0 ? thisPhoto.text.substring(0, thisPhoto.text.indexOf("(Photo")) : thisPhoto.text.substring(0, thisPhoto.text.indexOf("(AP")),
photoCredit = thisPhoto.text.indexOf("(Photo") > 0 ? thisPhoto.text.substring(thisPhoto.text.indexOf("(Photo")) : thisPhoto.text.substring(thisPhoto.text.indexOf("(AP")),
outputHTML = '<div id="photoContainer"><div class="header-wrap"><div class="header"><a id="photo-close" href="#"></a><h1></h1><h2>' + current.away.loc + " " + current.away.name + " at " + current.home.loc + " " + current.home.name + '</h2></div></div><div class="photo-viewport"><div class="photo-viewCol"><div id="photoloader"><img src="http://a.espncdn.com/i/gamecast/ajax-loader_trans.gif" alt="Loading..."></div><div id="photoWindow"><img src="' + thisPhoto.largeImg + '" oncontextmenu="return false;" /></div></div><div class="photo-infoCol"><div class="photo-controls"><div id="photo-prevArrow"></div><div id="photo-counter">' + (currentPhotoIndex + 1) + " of " + numPhotos + '</div><div id="photo-nextArrow"></div><div class="clear"></div></div><div class="photo-captionWrap"><p id="photo-caption">' + photoCaption + '</p><p id="photo-credit">' + photoCredit + '</p></div></div><div class="clear"></div><div class="thumbnails"><div id="thumbnail-header"><div class="button"></div><h2>' + espn.gamecast.translate("Thumbnails") + '</h2></div><div id="thumbnail-wrap" class="scroll-pane"><div><ul>';
for (var i = 0, n = photos.length; i < n; i++) {
thumbnailClass = photos[i].photoId == thisPhoto.photoId ? "current" : "";
outputHTML += PG.buildThumbHTML(photos[i], thumbnailClass);
}
outputHTML += '</ul><div class="clear"></div></div></div></div></div></div>';
return outputHTML;
};
PG.buildThumbHTML = function(photo, thumbnailClass) {
return '<li id="thumbnail-' + photo.photoId + '" class="thumbnail ' + thumbnailClass + '"><div class="thumbnail-crop"><img src="' + photo.img + '" oncontextmenu="return false;" /></div></li>';
};
})(jQuery);
espn.gamecast.nst = {};
(function($) {
NST = espn.gamecast.nst;
NST.update = function(note, newNote) {
if (note !== undefined) {
if (newNote) {
$("#nst").prepend(NST.builders.html(note, $("#nst").children(".nstNote:first-child").hasClass("even") ? "odd" : "even"));
} else {
var $note = $("#nst-" + note.id);
$note.replaceWith(NST.builders.html(note, $note.hasClass("even") ? "even" : "odd"));
}
if (note.id != 0) {
$("#nst-0").hide();
}
}
};
NST.build = function(notes) {
var outputHTML = "";
if (notes != undefined && notes.length > 0) {
for (var i = 0, n = notes.length; i < n; i++) {
outputHTML += NST.builders.html(notes[i], i % 2 == 0 ? "even" : "odd");
}
$("#nst-0").hide();
}
$("#nst").html(outputHTML);
};
NST.builders = {
html: function(note, noteClass) {
return '<div id="nst-' + note.id + '" class="nstNote ' + noteClass + '">' + note.note + "</div>";
}
};
})(jQuery);
espn.gamecast.oots = {};
(function($) {
var OOTS = espn.gamecast.oots;
OOTS.update = function(game) {
if (game !== undefined) {
var ootIndex = espn.gamecast.findIndex(OOTS.oots, game.id, "id");
if (ootIndex >= 0) {
var flashHome = game.home.score != OOTS.oots[ootIndex].homeScore,
flashAway = game.away.score != OOTS.oots[ootIndex].awayScore;
OOTS.oots[ootIndex].homeScore = game.home.score;
OOTS.oots[ootIndex].awayScore = game.away.score;
}
var $oot = $("#oot-" + game.id);
$oot.replaceWith(OOTS.builders.html.game(game));
if (flashHome || flashAway) {
var whichTeam = flashHome ? "home" : "away";
OOTS.highlightScore(game.id, whichTeam);
}
}
};
OOTS.shade = function(shadeIt) {
if (shadeIt) {
$("#oot-shade").show();
} else {
$("#oot-shade").hide();
}
};
OOTS.build = function() {
var games = espn.gamecast.master.games,
outputHTML = "";
OOTS.oots = [];
OOTS.personal.myTeams = {};
$.each(games, function(i, game) {
outputHTML += OOTS.builders.html.game(game, i + 1);
OOTS.oots.push(new OOTS.builders.json.game(game.id, game.home.score, game.away.score));
if (OOTS.personal.myTeams["10-" + game.home.id] === undefined) {
OOTS.personal.myTeams["10-" + game.home.id] = [];
}
OOTS.personal.myTeams["10-" + game.home.id].push("mlb-" + game.id);
if (OOTS.personal.myTeams["10-" + game.away.id] === undefined) {
OOTS.personal.myTeams["10-" + game.away.id] = [];
}
OOTS.personal.myTeams["10-" + game.away.id].push("mlb-" + game.id);
});
$("#oot-games").html(outputHTML);
OOTS.makeMyGames();
var magicScoreboardWidth = 872;
$("#oot-left").unbind("click");
$("#oot-right").unbind("click");
$("#oot-games li .oot-game-link").die();
$("#oot-left").bind("click", function() {
if ($("#oot-games li").length == 0) {
return;
}
var leftValue = -1 * $("#oot-games").position().left;
var games = $("#oot-games li");
for (var i = 0, n = games.length; i < n; i++) {
if (($(games[i]).position().left) > (leftValue - magicScoreboardWidth)) {
if ($("body").hasClass("iPadScroll")) {
$("#oot-wrap").find(".gc-oot-modbox").scrollLeft($(games[i]).position().left);
} else {
$("#oot-games").stop(true, true).animate({
left: "-" + $(games[i]).position().left + "px"
}, 500, function() {
$(this).css("left", "-" + $(games[i]).position().left + "px");
});
}
break;
}
}
});
$("#oot-right").bind("click", function() {
if ($("#oot-games li").length == 0) {
return;
}
var leftValue = -1 * $("#oot-games").position().left;
var games = $("#oot-games li");
for (var i = 0, n = games.length; i < n; i++) {
if (($(games[i]).position().left + $(games[i]).outerWidth()) > (leftValue + magicScoreboardWidth)) {
if ($("body").hasClass("iPadScroll")) {
$("#oot-wrap").find(".gc-oot-modbox").scrollLeft($(games[i]).position().left);
} else {
$("#oot-games").stop(true, true).animate({
left: "-" + $(games[i]).position().left + "px"
}, 500, function() {
$(this).css("left", "-" + $(games[i]).position().left + "px");
});
}
break;
}
}
});
$("#oot-games li .oot-game-link").live("click", function() {
try {
var $this = $(this),
id = $this.parent().get(0).id.split("-")[1];
espn.gamecast.debug("change game...");
if (id != espn.gamecast.master.current.id) {
espn.gamecast.debug("gameId = " + id);
espn.gamecast.publish("switchGame", [id]);
}
} catch (e) {
espn.gamecast.debug("change game error: " + e);
}
});
};
OOTS.updateTouchScrollWidth = function() {
if (espn.gamecast.isMobile) {
var ootsWidth = 0,
$oots = $("#oot-games");
$.each($oots.children("li"), function(i, val) {
ootsWidth += $(this).outerWidth() + 10;
});
$oots.css("width", ootsWidth + "px");
}
};
OOTS.builders = {
html: {
game: function(game, count) {
var isMobile = !!espn.gamecast.version,
status = espn.gamecast.getGameState(game.gameStatus),
winnerClass = "",
basesClass = "",
linkClass = (status != "pregame" || isMobile) && (game.pbpSourceId > 0) ? "oot-game-link" : "oot-game-wrap",
myClass = $("#oot-" + game.id).hasClass("my") ? "my" : "";
if (game.gameStatus != 8) {
if (status == "final" && game.away.score > game.home.score) {
winnerClass = "away";
} else {
if (status == "final" && game.away.score < game.home.score) {
winnerClass = "home";
}
}
}
var onBaseArray = game.bases.split("|");
for (var i = 0; i < 3; i++) {
if (parseInt(onBaseArray[i], 10) != 0) {
basesClass += "-1";
} else {
basesClass += "-0";
}
}
var previewLinkClass = !isMobile && game.previewLink != "" ? "showLink" : "",
recapLinkClass = !isMobile && game.recapLink != "" ? "showLink" : "",
previewLink = game.previewLink,
recapLink = game.recapLink;
statusText = game.gameStatus == 1 ? espn.gamecast.translate("Game Starts at") + " " + game.status1 + " " + game.status2.substring(0, 2) : game.status1, outText = game.outs == 1 ? espn.gamecast.translate("Out") : espn.gamecast.translate("Outs"), status1 = game.status1.replace("Alta", "A.").replace("Baja", "B.").replace("Mitad", "M."), pbpClass = game.pbpSourceId > 0 ? "" : "no-gamecast";
var outputHTML = '<li class="game ' + status + " " + myClass + " " + pbpClass + '" id="oot-' + game.id + '"><div class="gc-oot-status">';
if (!isMobile) {
outputHTML += '<div class="recapLink"><a href="' + recapLink + '" class="' + recapLinkClass + '" target="_blank">' + espn.gamecast.translate("Recap") + ' &#187;</a></div><div class="previewLink"><a href="' + previewLink + '" class="' + previewLinkClass + '" target="_blank">' + espn.gamecast.translate("Preview") + " &#187;</a></div>";
}
outputHTML += '</div><div class="' + linkClass + '"><div class="game-flag"><div class="flag-pregame">' + statusText + '</div><div class="flag-switch">' + espn.gamecast.translate("Switch to this Game") + '</div><div class="flag-nogc">' + espn.gamecast.translate("Gamecast Unavailable") + '</div></div><div class="status"><div class="clock">' + status1 + " " + game.status2 + '</div><div class="situation">' + game.balls + "-" + game.strikes + ", " + game.outs + " " + outText + '</div></div><div class="winner ' + winnerClass + '"></div><div class="rank"></div><div class="teams">' + game.away.abbrev.toUpperCase() + "<br/>" + game.home.abbrev.toUpperCase() + '</div><div class="score"><span class="away">' + game.away.score + '</span><br/><span class="home">' + game.home.score + '</span></div><div class="bases bases' + basesClass + '"></div></div><span class="sort">' + count + "</span></li>";
return outputHTML;
}
},
json: {
game: function(id, homeScore, awayScore) {
this.id = id;
this.homeScore = homeScore;
this.awayScore = awayScore;
}
}
};
OOTS.oots = [];
OOTS.highlightScore = function(gameId, which) {
var $oot = $("#oot-" + gameId);
$oot.addClass("highlight " + which);
setTimeout(function() {
$oot.removeClass("highlight home away");
}, 5000);
};
OOTS.personal = {
activeSport: "mlb",
myTeams: {}
};
OOTS.makeMyGames = function() {
var myTeams = OOTS.personal.myTeams;
var needToSort = false;
if ($.myespn) {
$.myespn.init({
success: function(data) {
var games = [];
var keys = [];
var $scoreboard = $("#oot-games");
if (data.myTeams !== undefined) {
var i = data.myTeams.length;
var sortOrder = 0;
while (i--) {
sortOrder--;
var key = data.myTeams[i].sport + "-" + data.myTeams[i].id;
var teamGames = myTeams[key];
if (teamGames != undefined) {
for (var g = 0; g < teamGames.length; g++) {
var nodeId = teamGames[g];
nodeId = nodeId.replace(settings.sport, "oot");
var $game = $("#" + nodeId);
if ($game.length == 0) {} else {
$game.addClass("my");
$(".sort", $game).html(sortOrder);
}
needToSort = true;
}
}
}
}
keys = null;
if (needToSort) {
$scoreboard.find("li").tsort("span.sort");
}
}
});
}
};
})(jQuery);
(function() {
var INTERVAL_TIME;
INTERVAL_TIME = 10;
window.Keanu = (function() {
function Keanu(id) {
if (!id || !document.getElementById(id)) {
return false;
}
this.canvas = document.getElementById(id);
this.ctx = this.canvas.getContext("2d");
this.isAnimating = false;
this.interval = null;
this.lastLoop = 0;
this.checkTimer = null;
this.triggering = false;
this.subscribers = {};
this.checkedDimensions = false;
this.clearX = 0;
this.clearY = 0;
this.clearW = this.canvas.width;
this.clearH = this.canvas.height;
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
this;
}
Keanu.prototype.subscribe = function(type, listener, zIndex) {
if (zIndex == null) {
zIndex = 0;
}
if (!this.subscribers[type]) {
this.subscribers[type] = [];
}
if (!this.subscribers[type][zIndex]) {
this.subscribers[type][zIndex] = [];
}
this.subscribers[type][zIndex].push(listener);
if (!this.interval && !this.isAnimating && type === "enterFrame") {
this.start();
}
};
Keanu.prototype.unsubscribe = function(type, listener, zIndex) {
var cutIt, i, j, s, sub, _len, _len2, _len3, _ref, _ref2, _this = this;
cutIt = function() {
if ((_this.subscribers.enterFrame && _this.subscribers.enterFrame.length === 0) || (_this.subscribers.enterFrame && _this.subscribers.enterFrame.length === 1 && _this.subscribers.enterFrame[0].length === 0)) {
_this.stop();
}
};
if (zIndex) {
if (this.subscribers[type] instanceof Array) {
if (this.subscribers[type][zIndex] instanceof Array) {
_ref = this.subscribers[type][zIndex];
for (i = 0, _len = _ref.length; i < _len; i++) {
sub = _ref[i];
if (sub === listener) {
this.subscribers[type][zIndex].splice(i, 1);
break;
}
}
}
}
} else {
if (this.subscribers[type] instanceof Array) {
_ref2 = this.subscribers[type];
for (i = 0, _len2 = _ref2.length; i < _len2; i++) {
sub = _ref2[i];
if (sub instanceof Array) {
for (j = 0, _len3 = sub.length; j < _len3; j++) {
s = sub[j];
if (s === listener) {
sub.splice(j, 1);
break;
}
}
} else {
if (this.subscribers === listener) {
this.subscribers[type].splice(i, 1);
break;
}
}
}
}
}
clearTimeout(this.checkTimer);
this.checkTimer = setTimeout(cutIt, 100);
};
Keanu.prototype.trigger = function(event) {
var s, sub, _i, _j, _len, _len2, _ref;
this.triggering = true;
if (typeof event === "string") {
event = {
type: event
};
}
if (!event.target) {
event.target = this;
}
if (!event.type) {
return;
}
if (this.subscribers[event.type] instanceof Array) {
_ref = this.subscribers[event.type];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
sub = _ref[_i];
if (sub instanceof Array) {
for (_j = 0, _len2 = sub.length; _j < _len2; _j++) {
s = sub[_j];
if (s) {
s.call(this, event);
}
}
}
}
}
this.triggering = false;
};
Keanu.prototype.start = function() {
var looper, _this = this;
looper = function() {
if (_this.isAnimating || _this.interval) {
if (_this.lastLoop === 0) {
_this.lastLoop = +(new Date);
}
_this.clear();
if ((+(new Date)) - _this.lastLoop > 30000) {
_this.reset();
} else {
_this.lastLoop = +(new Date);
_this.trigger("enterFrame");
}
if (window.requestAnimationFrame) {
window.requestAnimationFrame(looper, _this.canvas);
}
}
};
if (window.requestAnimationFrame && !this.isAnimating) {
this.isAnimating = true;
window.requestAnimationFrame(looper, this.canvas);
this.trigger("start");
} else {
if (!window.requestAnimationFrame && !this.interval) {
this.interval = setInterval(looper, INTERVAL_TIME);
this.trigger("start");
}
}
};
Keanu.prototype.stop = function() {
this.isAnimating = false;
clearInterval(this.interval);
this.interval = null;
this.clear();
this.trigger("stop");
};
Keanu.prototype.reset = function() {
var doIt, _this = this;
doIt = function() {
_this.subscribers = [];
clearInterval(_this.checkTimer);
_this.checkTimer = null;
_this.stop();
_this.lastLoop = 0;
return _this.trigger("reset");
};
if (this.triggering) {
setTimeout(this.reset, 5);
} else {
doIt();
}
};
Keanu.prototype.clear = function() {
var h, w, x, y;
x = 0;
y = 0;
w = this.canvas.width;
h = this.canvas.height;
this.ctx.clearRect(x, y, w, h);
this.checkedDimensions = false;
this.clearX = 0;
this.clearY = 0;
this.clearW = 0;
this.clearH = 0;
};
Keanu.prototype.setDimension = function(dim, val, fn) {
if (!isNaN(dim)) {
return fn && fn(dim, val);
} else {
return val;
}
};
Keanu.prototype.setDimensions = function(dims) {
if (this.checkedDimensions) {
this.clearX = this.setDimension(this.clearX, dims.x, Math.min);
this.clearY = this.setDimension(this.clearY, dims.y, Math.min);
this.clearW = this.setDimension(this.clearW, dims.w, Math.max);
this.clearH = this.setDimension(this.clearH, dims.h, Math.max);
} else {
this.clearX = dims.x;
this.clearY = dims.y;
this.clearW = dims.w;
this.clearH = dims.h;
this.checkedDimensions = true;
}
};
Keanu.prototype.isEmpty = function(o) {
var i, p, _i, _j, _len, _len2, _ref;
for (_i = 0, _len = o.length; _i < _len; _i++) {
p = o[_i];
if (o[p] instanceof Array && o[p].length > 0) {
_ref = o[p];
for (_j = 0, _len2 = _ref.length; _j < _len2; _j++) {
i = _ref[_j];
if (o[p][i] instanceof Array && o[p][i].length > 0) {
return false;
}
}
}
}
return true;
};
Keanu.prototype.getIntervalTime = function() {
return INTERVAL_TIME;
};
Keanu.prototype.tweens = {
linear: function(t, b, c, d) {
return c * t / d + b;
},
easeIn: function(t, b, c, d) {
return c * (t /= d) * t + b;
},
easeOut: function(t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
easeInOut: function(t, b, c, d) {
if (t /= d / 2 < 1) {
return c / 2 * t * t * b;
} else {
return -c / 2 * ((--t) * (t - 2) - 1) + b;
}
},
quadraticBezierCurve: function(t, p0, p1, p2) {
return ~~(Math.pow(1 - t, 2) * p0 + 2 * (1 - t) * t * p1 + Math.pow(t, 2) * p2);
}
};
return Keanu;
})();
window.Keanu.modules = {};
}).call(this);
(function() {
var Animation, Neo;
Neo = {
defaults: {
fillStyle: "rgb(255, 255, 255)",
lineWidth: "0",
strokeStyle: "rgb(255, 255, 255)"
},
shapes: {
line: function(data) {
var ctx, destination, destinationX, destinationY, origin, originX, originY, stroke, styles, width;
if (!data) {
return;
}
origin = data.origin || [];
destination = data.destination || [];
styles = data.styles || {};
originX = origin[0] || 0;
originY = origin[1] || 0;
destinationX = destination[0] || 0;
destinationY = destination[1] || 0;
width = styles.lineWidth || Neo.defaults.lineWidth;
stroke = styles.strokeStyle || Neo.defaults.strokeStyle;
ctx = data.ctx || null;
if (ctx) {
ctx.beginPath();
ctx.strokeStyle = stroke;
ctx.lineWidth = width;
ctx.moveTo(originX, originY);
ctx.lineTo(destinationX, destinationY);
ctx.stroke();
ctx.closePath();
}
},
circle: function(data) {
var ctx, fill, r, stroke, styles, width, x, y;
if (!data) {
return;
}
styles = data.styles || {};
x = data.x || 0;
y = data.y || 0;
r = data.r || 0;
fill = styles.fillStyle || Neo.defaults.fillStyle;
stroke = styles.strokeStyle || Neo.defaults.strokeStyle;
width = styles.lineWidth || Neo.defaults.lineWidth;
ctx = data.ctx || null;
if (ctx) {
ctx.fillStyle = fill;
ctx.strokeStyle = stroke;
ctx.width = width;
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
}
};
Animation = (function() {
function Animation(keanu, opts, duration) {
var animationMiddle, callback, change, changed, control, controlRadius, controlX, controlY, currentRadius, currentX, currentY, destination, destinationRadius, destinationX, destinationY, draw, ease, easing, frame, hideTrails, instance, intervalTime, isArc, origin, originRadius, originX, originY, rChange, self, styles, tick, tickerStep, trailColor, xChange, yChange, z;
isArc = opts.control || false;
instance = opts.instance;
origin = opts.origin || [];
originX = origin[0] || 0;
originY = origin[1] || 0;
originRadius = origin[2] || 0;
if (isArc) {
control = opts.control || [];
controlX = control[0] || 0;
controlY = control[1] || 0;
controlRadius = control[2] || 0;
}
destination = opts.destination || [];
destinationX = destination[0] || 0;
destinationY = destination[1] || 0;
destinationRadius = destination[2] || 0;
draw = opts.draw || Neo.shapes.circle;
trailColor = opts.trailColor || "255, 255, 255, ";
ease = opts.easing || "linear";
hideTrails = opts.hideTrails;
callback = opts.callback || function() {};
styles = opts.styles || {};
duration = duration || 1000;
z = opts.zIndex || 0;
if (isArc) {
animationMiddle = opts.animationMiddle || 2;
}
this.trailStates = [];
this.keepStates = opts.keepStates || 15;
if (isArc) {
originX = originX !== controlX ? originX : originX + 1;
originY = originY !== controlY ? originY : originY + 1;
}
currentX = originX;
currentY = originY;
currentRadius = originRadius;
easing = keanu.tweens[ease];
intervalTime = instance.intervalTime;
frame = 0;
tick = 0;
tickerStep = duration / intervalTime;
xChange = destinationX - originX;
yChange = destinationY - originY;
if (isArc) {
rChange = controlRadius - originRadius;
} else {
rChange = destinationRadius - originRadius;
}
changed = false;
self = this;
change = function() {
var alpha, i, len, rad;
if (!instance.hideTrails) {
if (!hideTrails) {
len = self.trailStates.length;
if (len > 0) {
alpha = 0.1;
rad = 0.85;
i = len - 1;
while (i >= 0) {
Neo.shapes.circle({
ctx: keanu.ctx,
x: self.trailStates[i][0] || 0,
y: self.trailStates[i][1] || 0,
r: (self.trailStates[i][2] * rad) || 0,
styles: {
fillStyle: "rgba(" + trailColor + " " + alpha + ")",
strokeStyle: "rgba(0, 0, 0, 0)"
}
});
keanu.setDimensions({
x: self.trailStates[i][0] - (self.trailStates[i][2] * rad),
y: self.trailStates[i][1] - (self.trailStates[i][2] * rad),
w: self.trailStates[i][0] + (self.trailStates[i][2] * rad),
h: self.trailStates[i][1] + (self.trailStates[i][2] * rad)
});
alpha += 0.05;
if (rad < 0.98) {
rad += 0.02;
}
i--;
}
}
}
}
currentX = easing(frame, originX, xChange, tickerStep);
currentY = easing(frame, originY, yChange, tickerStep);
if (isArc) {
if (frame < duration / animationMiddle) {
currentRadius = easing(frame, originRadius, rChange, duration);
} else {
if (!changed) {
rChange = destinationRadius - currentRadius;
changed = true;
}
currentRadius = easing(frame, controlRadius, rChange, duration);
}
} else {
currentRadius = easing(frame, originRadius, rChange, tickerStep);
}
if (isArc) {
if (controlX !== 0) {
currentX = keanu.tweens.quadraticBezierCurve((originX - currentX) / (originX - destinationX), originX, controlX, destinationX);
}
if (controlY !== 0) {
currentY = keanu.tweens.quadraticBezierCurve((originY - currentY) / (originY - destinationY), originY, controlY, destinationY);
}
}
if (frame % instance.step === 0 && (!instance.hideTrails && !hideTrails)) {
self.handleTrailState([currentX, currentY, currentRadius]);
}
draw && draw.call(instance, {
ctx: keanu.ctx,
x: currentX,
y: currentY,
r: currentRadius,
styles: {
fillStyle: styles.fillStyle || "rgb(255, 255, 255)",
strokeStyle: styles.strokeStyle || "rgb(255, 255, 255)",
lineWidth: styles.lineWidth || "0"
}
});
frame++;
tick += intervalTime;
if (tick >= duration) {
self.trailStates = [];
keanu.unsubscribe("enterFrame", change, z);
return callback && callback();
}
};
keanu.subscribe("enterFrame", change, z);
return;
}
Animation.prototype.handleTrailState = function(state) {
var i, loopLen, temp;
temp = [];
loopLen = this.trailStates.length >= this.keepStates ? this.keepStates : this.trailStates.length;
temp.push(state);
for (i = 0; 0 <= loopLen ? i < loopLen : i > loopLen; 0 <= loopLen ? i++ : i--) {
temp.push(this.trailStates[i]);
}
this.trailStates = temp;
};
return Animation;
})();
Neo.Animation = Animation;
window.Neo = Neo;
}).call(this);
(function() {
var __hasProp = Object.prototype.hasOwnProperty;
(function($) {
var BALL_RADIUS, BEZ, Field, GROUNDER_RADIUS, POPFLY_RADIUS, SHADOW_RADIUS, MAP_MAX, HALF_MAP, FAR_WALL, BACK_WALL;
BALL_RADIUS = 3;
GROUNDER_RADIUS = 2.5;
POPFLY_RADIUS = 5.5;
SHADOW_RADIUS = 1.5;
BEZ = -20;
MAP_MAX = 250;
HALF_MAP = MAP_MAX / 2;
FAR_WALL = 15;
BACK_WALL = 170;
Field = (function() {
function Field(opts) {
if (!opts) {
return;
}
this.keanu = new Keanu(opts.canvasId || "field-render");
this.intervalTime = this.keanu.getIntervalTime();
this.hideTrails = opts.hideTrails;
this.step = opts.step || 3;
this.showingSprayChart = false;
this.sprayChartOn = false;
this.showingBaserunners = false;
this.showingDefense = false;
this.baserunners = [0, 0, 0];
this.isAnimating = false;
this.pitchQueue = [];
this.batterName = "";
this.sprayChart = {
outLeftPct: 0,
outMidPct: 0,
outRightPct: 0,
infLeftPct: 0,
infMidPct: 0,
infRightPct: 0
};
this.fieldContainer = $(".field-container");
this.sprayChartCaption = $("#spray-chart-caption");
this.sprayChartPlayer = $("#spray-chart-player");
this.$baserunners = [$("#br-1"), $("#br-2"), $("#br-3")];
this.htsRunning = this.httRunning = this.fttRunning = this.hthRunning = this.fthRunning = this.sthRunning = this.tthRunning = this.sttRunning = this.ftsRunning = this.htfRunning = false;
this.firstBase = $("#first-baseman");
this.secondBase = $("#second-baseman");
this.thirdBase = $("#third-baseman");
this.shortstop = $("#shortstop-fielder");
this.pitcher = $("#pitcher-fielder");
this.catcher = $("#catcher-fielder");
this.leftField = $("#left-fielder");
this.rightField = $("#right-fielder");
this.centerField = $("#center-fielder");
this.max = 470;
this.homeX = 235;
this.homeY = 147;
this.rubberX = 235;
this.rubberY = 110;
this.firstX = 310;
this.firstY = 110;
this.secondX = 235;
this.secondY = 84;
this.thirdX = 160;
this.thirdY = 110;
this.home = [this.homeX, this.homeY, 5];
this.first = [this.firstX, this.firstY, 4];
this.second = [this.secondX, this.secondY, 3];
this.third = [this.thirdX, this.thirdY, 4];
this.plate = [this.homeX, this.homeY, BALL_RADIUS];
this.size = {
width: 475,
height: 173
};
this.toggleBaserunners();
this.adjustDefense();
}
Field.prototype.shadow = {
fillStyle: "rgb(0, 0, 0)",
lineWidth: 1,
strokeStyle: "rgb(33, 33, 33)"
};
Field.prototype.getDiminishingPercentage = function(start, end, distance) {
var backDistance, foreDistance, maxPercent, minPercent, percent;
foreDistance = distance || start - FAR_WALL;
backDistance = distance || BACK_WALL - start;
minPercent = 0.3;
maxPercent = 0.1;
percent = 0;
if (end < start) {
percent = 0.75 - ((start - end) / foreDistance * minPercent);
percent = percent < maxPercent ? maxPercent : percent;
} else {
if (end > start) {
percent = (end - start) / backDistance * maxPercent;
percent = percent > maxPercent ? maxPercent : percent;
percent += 1;
}
}
return percent;
};
Field.prototype.transformX = function(x) {
var diff, left, mid, newx, pc, right;
if (!x) {
return 0;
}
diff = HALF_MAP - x;
pc = diff / 25;
mid = this.homeX / 125;
left = this.thirdX / 100;
right = this.firstX / (pc > -1.5 ? 150 : 165);
newx = x * mid;
if (pc > 0 && Math.abs(diff <= 25)) {
newx = x * (mid - (mid - left) * pc);
} else {
if (pc < 0 && Math.abs(diff <= 25)) {
newx = x * (mid + (mid - right) * pc);
}
}
return newx;
};
Field.prototype.transformY = function(y) {
var radians, newy;
if (!y) {
return 0;
}
radians = 0;
if (y < 150) {
if (this.size.width === 475) {
radians = 0.95 - ((0.95 - 1.1) * ((150 - y) / 115));
} else {
if (this.size.width === 320) {
radians = 1.14 - ((1.14 - 1.29) * ((150 - y) / 115));
}
}
} else {
if (y >= 150 && y <= 195) {
radians = this.size.width === 320 ? 1.13 : 0.89;
} else {
if (y > 195) {
radians = this.size.width === 320 ? 1.05 : 0.75;
}
}
}
newy = (y * Math.cos(radians)) + (1 * -Math.sin(radians));
return newy;
};
Field.prototype.isEmptyObject = function(o) {
var p;
for (p in o) {
if (!__hasProp.call(o, p)) {
continue;
}
return false;
}
return true;
};
Field.prototype.trailColors = {
drive: "247, 215, 4,",
popup: "42, 151, 234,",
grounder: "61, 244, 214,",
pitch: "229, 51, 48,"
};
Field.prototype.updateBatter = function(name) {
this.batterName = name;
return this.sprayChartPlayer.text(name);
};
Field.prototype.pitch = function(data) {
if (this.isAnimating) {
this.pitchQueue.push(data);
} else {
this.animatePitch(data);
}
};
Field.prototype.checkPitchQueue = function() {
if (this.pitchQueue.length > 0) {
this.animatePitch(this.pitchQueue.shift());
}
};
Field.prototype.animatePitch = function(data) {
var duration, endCallback, endRadius, hit, hitType, pitchCallback, self, types;
self = this;
this.isAnimating = true;
hitType = String(data.type).toLowerCase() || "l";
duration = data.duration;
pitchCallback = function() {
data.pitchCallback && data.pitchCallback();
};
endCallback = function() {
data.callback && data.callback();
self.mark({
x: data.x,
y: data.y,
isHit: data.isHit
});
self.checkPitchQueue();
self.isAnimating = false;
};
endRadius = BALL_RADIUS * this.getDiminishingPercentage(this.homeY, this.rubberY);
types = {
l: this.drive,
p: this.popup,
f: this.popup,
g: this.grounder,
b: this.bunt
};
hit = function(data) {
if (!data) {
return;
}
if (types[hitType]) {
setTimeout(function() {
types[hitType].call(self, {
x: data.x,
y: data.y,
duration: duration,
callback: endCallback
});
}, 15);
} else {
endCallback && endCallback();
}
};
new Neo.Animation(this.keanu, {
instance: this,
origin: [this.rubberX, this.rubberY, endRadius],
destination: [this.homeX, this.homeY, BALL_RADIUS],
trailColor: this.trailColors.pitch,
easing: "easeOut",
zIndex: 50,
callback: function() {
pitchCallback();
self.trailStates = [];
hit(data);
}
}, 500);
};
Field.prototype.drive = function(data) {
var callback, duration, endRadius, x, xDir, y;
if (!data) {
return;
}
this.isAnimating = true;
duration = data.duration || 2000;
callback = function() {
data.callback && data.callback();
this.isAnimating = false;
};
xDir = this.homeX > data.x ? -1 : 1;
x = this.transformX(data.x);
y = this.transformY(data.y);
endRadius = BALL_RADIUS * this.getDiminishingPercentage(this.homeY, y);
new Neo.Animation(this.keanu, {
instance: this,
origin: this.plate,
destination: [x, y, endRadius],
easing: "easeOut",
trailColor: this.trailColors.drive,
callback: callback,
zIndex: 50
}, duration);
};
Field.prototype.popup = function(data) {
var callback, controlX, controlY, duration, endRadius, x, y;
if (!data) {
return;
}
this.isAnimating = true;
duration = data.duration || 3000;
x = this.transformX(data.x);
y = this.transformY(data.y);
endRadius = BALL_RADIUS * this.getDiminishingPercentage(this.homeY, y);
controlX = this.homeX - ((this.homeX - x) / 2);
controlY = BEZ - (y / 2);
callback = function() {
data.callback && data.callback();
this.isAnimating = false;
};
x = x === this.homeX ? x - 1 : x;
this.drawShadow({
x: x,
y: y,
duration: duration
});
new Neo.Animation(this.keanu, {
instance: this,
origin: this.plate,
control: [controlX, controlY, POPFLY_RADIUS],
destination: [x, y, endRadius],
easing: "easeOut",
trailColor: this.trailColors.popup,
callback: callback,
zIndex: 50
}, duration);
};
Field.prototype.grounder = function(data) {
var callback, controlX, controlX2, controlY, controlY2, duration, firstBounce, impact, secondBounce, x, xDiff, xDir, xImpact, xImpact2, y, yDiff, yImpact, yImpact2, _this = this;
if (!data) {
return;
}
this.isAnimating = true;
x = this.transformX(data.x);
y = this.transformY(data.y);
duration = data.duration || 1500;
callback = function() {
data.callback && data.callback();
this.isAnimating = false;
};
xDiff = this.homeX - x;
yDiff = this.homeY - y;
impact = 0.85;
xImpact = this.homeX - (impact * xDiff);
yImpact = this.homeY - (impact * yDiff);
controlX = xImpact;
controlY = yImpact + BEZ / 4;
xImpact2 = xImpact - (0.5 * (xImpact - x));
yImpact2 = yImpact - (0.5 * (yImpact - y));
controlX2 = xImpact2;
controlY2 = yImpact2 + BEZ / 7;
xDir = this.homeX > data.x ? -1 : 1;
secondBounce = function() {
new _this.Impact({
instance: _this,
x: xImpact2,
y: yImpact2
});
_this.drawShadow({
origin: [xImpact2, yImpact2 + 2, SHADOW_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact2)],
destination: [x, y, SHADOW_RADIUS * _this.getDiminishingPercentage(_this.homeY, y)],
duration: duration * 0.075
});
new Neo.Animation(_this.keanu, {
instance: _this,
origin: [xImpact2, yImpact2, GROUNDER_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact2)],
control: [controlX2, controlY2, GROUNDER_RADIUS * _this.getDiminishingPercentage(yImpact2, yImpact2 - 10)],
destination: [x, y, GROUNDER_RADIUS * _this.getDiminishingPercentage(_this.homeY, y)],
easing: "easeOut",
hideTrails: true,
trailColor: _this.trailColors.grounder,
callback: callback,
zIndex: 50
}, duration * 0.1);
};
firstBounce = function() {
new _this.Impact({
instance: _this,
x: xImpact,
y: yImpact
});
_this.drawShadow({
origin: [xImpact, yImpact, SHADOW_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact)],
destination: [xImpact2, yImpact2 + 1, SHADOW_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact2)],
easing: "linear",
duration: duration * 0.075
});
new Neo.Animation(_this.keanu, {
instance: _this,
origin: [xImpact, yImpact, GROUNDER_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact)],
control: [controlX, controlY, GROUNDER_RADIUS * _this.getDiminishingPercentage(yImpact, yImpact - 10)],
destination: [xImpact2, yImpact2, GROUNDER_RADIUS * _this.getDiminishingPercentage(_this.homeY, yImpact2)],
easing: "linear",
hideTrails: true,
trailColor: _this.trailColors.grounder,
callback: secondBounce,
zIndex: 50
}, duration * 0.1);
};
new Neo.Animation(this.keanu, {
instance: this,
origin: [this.homeX, this.homeY, GROUNDER_RADIUS],
destination: [xImpact, yImpact, GROUNDER_RADIUS * this.getDiminishingPercentage(_this.homeY, yImpact)],
easing: "linear",
trailColor: this.trailColors.grounder,
callback: firstBounce,
zIndex: 50
}, duration * 0.8);
};
Field.prototype.bunt = function(data) {
if (!data) {
return;
}
this.grounder({
x: data.x,
y: data.y,
duration: data.duration,
callback: data.callback
});
};
Field.prototype.drawShadow = function(data) {
var destination, duration, easing, origin;
if (!data) {
return;
}
origin = data.origin || [this.homeX, this.homeY, SHADOW_RADIUS];
destination = data.destination || [data.x, data.y, SHADOW_RADIUS];
duration = data.duration || 1000;
easing = data.easing || "easeOut";
new Neo.Animation(this.keanu, {
instance: this,
origin: origin,
destination: destination,
easing: easing,
zIndex: 2,
hideTrails: true,
styles: this.shadow
}, duration);
};
Field.prototype.run = function(data) {
var callback, destination, duration, origin;
if (!data) {
return;
}
origin = data.origin || this.first;
destination = data.destination || this.second;
duration = data.duration || 1000;
callback = data.callback || function() {};
new Neo.Animation(this.keanu, {
instance: this,
origin: origin,
destination: destination,
easing: "linear",
hideTrails: true,
callback: callback,
zIndex: 50,
styles: {
fillStyle: "#FFFA70",
strokeStyle: "#FFFA70",
lineWidth: "0"
}
}, duration);
};
Field.prototype.homeToFirst = function(callback) {
var self;
self = this;
this.htfRunning = true;
this.run({
origin: this.home,
destination: this.first,
callback: function() {
self.htfRunning = false;
callback && callback.call(self);
}
});
};
Field.prototype.firstToSecond = function(callback) {
var self;
self = this;
this.ftsRunning = true;
this.run({
origin: this.first,
destination: this.second,
callback: function() {
self.ftsRunning = false;
callback && callback.call(self);
}
});
};
Field.prototype.secondToThird = function(callback) {
var self;
self = this;
this.sttRunning = true;
this.run({
origin: this.second,
destination: this.third,
callback: function() {
self.sttRunning = false;
callback && callback.call(self);
}
});
};
Field.prototype.thirdToHome = function(callback) {
var self;
self = this;
this.tthRunning = true;
this.run({
origin: this.third,
destination: this.home,
callback: function() {
self.tthRunning = false;
callback && callback.call(self);
}
});
};
Field.prototype.secondToHome = function(callback) {
var self;
self = this;
this.sthRunning = true;
this.secondToThird(function() {
this.thirdToHome(function() {
self.sthRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.firstToHome = function(callback) {
var self;
self = this;
this.fthRunning = true;
this.firstToSecond(function() {
this.secondToHome(function() {
self.fthRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.homeToHome = function(callback) {
var self;
self = this;
this.hthRunning = false;
this.homeToFirst(function() {
this.firstToHome(function() {
self.hthRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.firstToThird = function(callback) {
var self;
self = this;
this.fttRunning = true;
this.firstToSecond(function() {
this.secondToThird(function() {
self.fttRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.homeToThird = function(callback) {
var self;
self = this;
this.httRunning = true;
this.homeToFirst(function() {
this.firstToThird(function() {
self.httRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.homeToSecond = function(callback) {
var self;
self = this;
this.htsRunning = true;
this.homeToFirst(function() {
this.firstToSecond(function() {
self.htsRunning = false;
callback && callback.call(self);
});
});
};
Field.prototype.Impact = function(data) {
var draw, duration, instance, mark, tick, x, y;
if (!data) {
return;
}
instance = data.instance;
x = data.x || 0;
y = data.y || 0;
tick = 0;
mark = 5;
duration = 150;
draw = function() {
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x - BALL_RADIUS, y - (BALL_RADIUS / 3)],
destination: [x - BALL_RADIUS - mark / 2, y - (BALL_RADIUS / 2) - (mark / 2)]
});
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x - BALL_RADIUS, y],
destination: [x - BALL_RADIUS - mark, y]
});
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x - BALL_RADIUS, y + (BALL_RADIUS / 3)],
destination: [x - BALL_RADIUS - mark / 2, y + (BALL_RADIUS / 2) + (mark / 2)]
});
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x + BALL_RADIUS, y + (BALL_RADIUS / 3)],
destination: [x + BALL_RADIUS + mark / 2, y - (BALL_RADIUS / 2) - (mark / 2)]
});
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x + BALL_RADIUS, y],
destination: [x + BALL_RADIUS + mark, y]
});
Neo.shapes.line({
ctx: instance.keanu.ctx,
origin: [x + BALL_RADIUS, y + (BALL_RADIUS / 3)],
destination: [x + BALL_RADIUS + mark / 2, y + (BALL_RADIUS / 2) + (mark / 2)]
});
tick += instance.intervalTime;
if (tick >= duration) {
instance.keanu.unsubscribe("enterFrame", draw, 60);
}
};
instance.keanu.subscribe("enterFrame", draw, 60);
};
Field.prototype.mark = function(data) {
var cssClass;
if (!data) {
return;
}
cssClass = data.isHit ? "hit" : "out";
if (data.y > 0 && data.x > 0) {
$("<a href='#' class='hit-marker " + cssClass + "' style='display: none; top: " + ((this.transformY(data.y))) + "px; left: " + ((this.transformX(data.x)) - 9) + "px'></a>").appendTo(".field-container").fadeIn(500);
}
};
Field.prototype.addPlayResult = function(text) {
var $marker;
if (settings.lang !== "es") {
$marker = this.fieldContainer.find(".hit-marker");
if ($marker.length > 0) {
$marker.attr("title", text);
}
}
};
Field.prototype.removeMarks = function() {
var $markers;
$markers = this.fieldContainer.find(".hit-marker");
if ($markers.length > 0) {
$markers.remove();
}
};
Field.prototype.sprayText = function(x, y, percentage) {
var alpha, ctx, height, textX, textY, width;
ctx = this.keanu.ctx;
width = 35;
height = 15;
alpha = 0.6;
textX = x + 17;
textY = y + 11;
ctx.fillStyle = "rgba(0, 0, 0, " + alpha + ")";
ctx.fillRect(x, y, width, height);
ctx.fillStyle = "#FFF";
ctx.font = "8pt Verdana";
ctx.textAlign = "center";
ctx.fillText(percentage, textX, textY);
};
Field.prototype.drawLeftField = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(93, 64);
ctx.bezierCurveTo(93, 64, 109, 57, 132, 53);
ctx.lineTo(110, 15);
ctx.bezierCurveTo(110, 15, 67, 19, 20, 27);
ctx.lineTo(93, 64);
} else {
ctx.moveTo(137, 95);
ctx.bezierCurveTo(137, 95, 172, 83, 197, 80);
ctx.lineTo(163, 23);
ctx.bezierCurveTo(163, 23, 91, 28, 31, 42);
ctx.lineTo(137, 95);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(77, 33, percentage + "%");
} else {
this.sprayText(115, 50, percentage + "%");
}
} catch (e) {}
};
Field.prototype.drawCenterField = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(134, 53);
ctx.bezierCurveTo(134, 53, 160, 51, 187, 53);
ctx.lineTo(210, 15);
ctx.bezierCurveTo(210, 15, 160, 12, 112, 15);
ctx.lineTo(134, 53);
} else {
ctx.moveTo(199, 80);
ctx.bezierCurveTo(199, 80, 235, 75, 278, 80);
ctx.lineTo(314, 23);
ctx.bezierCurveTo(314, 23, 235, 15, 165, 23);
ctx.lineTo(199, 80);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(146, 25, percentage + "%");
} else {
this.sprayText(217, 39, percentage + "%");
}
} catch (e) {}
};
Field.prototype.drawRightField = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(188, 54);
ctx.bezierCurveTo(188, 54, 208, 58, 225, 64);
ctx.lineTo(297, 27);
ctx.bezierCurveTo(297, 27, 385, 30, 212, 16);
ctx.lineTo(188, 54);
} else {
ctx.moveTo(280, 80);
ctx.bezierCurveTo(280, 80, 304, 84, 333, 95);
ctx.lineTo(440, 40);
ctx.bezierCurveTo(440, 40, 385, 30, 316, 23);
ctx.lineTo(280, 80);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(215, 33, percentage + "%");
} else {
this.sprayText(320, 50, percentage + "%");
}
} catch (e) {}
};
Field.prototype.drawThirdBase = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(154, 98);
ctx.lineTo(156, 98);
ctx.lineTo(134, 55);
ctx.bezierCurveTo(134, 55, 111, 59, 92, 65);
ctx.lineTo(154, 98);
} else {
ctx.moveTo(232, 144);
ctx.lineTo(234, 144);
ctx.lineTo(199, 81);
ctx.bezierCurveTo(199, 81, 166, 85, 137, 97);
ctx.lineTo(232, 144);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(107, 68, percentage + "%");
} else {
this.sprayText(161, 92, percentage + "%");
}
} catch (e) {}
};
Field.prototype.drawSecondBase = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(157, 98);
ctx.lineTo(135, 55);
ctx.bezierCurveTo(135, 55, 158, 52, 185, 56);
ctx.lineTo(157, 98);
} else {
ctx.moveTo(235, 144);
ctx.lineTo(200, 81);
ctx.bezierCurveTo(200, 81, 235, 77, 277, 82);
ctx.lineTo(235, 144);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(148, 62, percentage + "%");
} else {
this.sprayText(220, 82, percentage + "%");
}
} catch (e) {}
};
Field.prototype.drawFirstBase = function(percentage) {
var ctx;
ctx = this.keanu.ctx;
ctx.beginPath();
if (this.size.width === 320) {
ctx.moveTo(158, 98);
ctx.lineTo(159, 98);
ctx.lineTo(224, 66);
ctx.bezierCurveTo(224, 66, 207, 59, 186, 56);
ctx.lineTo(158, 98);
} else {
ctx.moveTo(236, 144);
ctx.lineTo(238, 144);
ctx.lineTo(334, 98);
ctx.bezierCurveTo(334, 98, 305, 86, 278, 82);
ctx.lineTo(236, 144);
}
ctx.fillStyle = "rgba(0, 0, 0, " + (percentage / 100) + ")";
ctx.fill();
ctx.closePath();
try {
if (this.size.width === 320) {
this.sprayText(192, 68, percentage + "%");
} else {
this.sprayText(279, 92, percentage + "%");
}
} catch (e) {}
};
Field.prototype.showSprayChart = function() {
var draw, _this = this;
this.sprayChartOn = true;
draw = function() {
_this.drawLeftField(_this.sprayChart.outLeftPct);
_this.drawCenterField(_this.sprayChart.outMidPct);
_this.drawRightField(_this.sprayChart.outRightPct);
_this.drawThirdBase(_this.sprayChart.infLeftPct);
_this.drawSecondBase(_this.sprayChart.infMidPct);
_this.drawFirstBase(_this.sprayChart.infRightPct);
if (!_this.sprayChartOn) {
_this.keanu.unsubscribe("enterFrame", draw, 50);
}
};
this.sprayChartPlayer.text(this.batterName);
this.sprayChartCaption.removeClass("hideMe").addClass("showMe");
this.keanu.subscribe("enterFrame", draw, 50);
};
Field.prototype.hideSprayChart = function() {
this.sprayChartOn = false;
this.sprayChartCaption.removeClass("showMe").addClass("hideMe");
this.sprayChartPlayer.text("");
};
Field.prototype.toggleSprayChart = function() {
if (this.showingSprayChart) {
this.hideSprayChart();
$("#toggle-spray-chart").removeClass("on round-btn-small-on").addClass("round-btn-small").text(espn.gamecast.translate("SPRAY CHART OFF"));
} else {
if (this.showingBaserunners) {
this.toggleBaserunners();
}
if (this.showingDefense) {
this.toggleDefense();
}
this.showSprayChart();
$("#toggle-spray-chart").removeClass("round-btn-small").addClass("on rount-btn-small-on").text(espn.gamecast.translate("SPRAY CHART ON"));
}
this.showingSprayChart = !this.showingSprayChart;
};
Field.prototype.showDefense = function() {
$(".fielder").show();
};
Field.prototype.hideDefense = function() {
$(".fielder").hide();
};
Field.prototype.updateDefense = function(data) {
var empty, val, vals, _i, _len;
empty = {
lastName: "",
id: "",
position: "",
href: ""
};
vals = [{
position: "first-baseman",
data: data.first || empty
}, {
position: "second-baseman",
data: data.second || empty
}, {
position: "third-baseman",
data: data.third || empty
}, {
position: "shortstop-fielder",
data: data["short"] || empty
}, {
position: "pitcher-fielder",
data: data.pitcher || empty
}, {
position: "catcher-fielder",
data: data.catcher || empty
}, {
position: "left-fielder",
data: data.left || empty
}, {
position: "center-fielder",
data: data.center || empty
}, {
position: "right-fielder",
data: data.right || empty
}];
for (_i = 0, _len = vals.length; _i < _len; _i++) {
val = vals[_i];
$("#" + val.position).text(val.data.lastName).attr({
"data-playerId": val.data.id,
"data-position": val.data.position,
href: val.data.href
});
}
};
Field.prototype.updatePitcher = function(pitcher) {
$("#pitcher-fielder").text(pitcher.lastName).attr({
"data-playerId": pitcher.id,
"data-position": "P",
href: pitcher.href
});
};
Field.prototype.toggleDefense = function() {
if (this.showingDefense) {
this.hideDefense();
$("#toggle-defense").removeClass("on round-btn-small-on").addClass("round-btn-small").text(espn.gamecast.translate("DEFENSE OFF"));
} else {
if (this.showingSprayChart) {
this.toggleSprayChart();
}
if (this.showingBaserunners) {
this.toggleBaserunners();
}
this.showDefense();
this.adjustDefense();
$("#toggle-defense").removeClass("round-btn-small").addClass("on round-btn-small-on").text(espn.gamecast.translate("DEFENSE ON"));
}
this.showingDefense = !this.showingDefense;
};
Field.prototype.adjustDefense = function() {
var width;
width = this.rubberX * 2;
this.leftField.css("left", width * 0.2 - (this.leftField.innerWidth() / 2));
this.centerField.css("left", width * 0.5 - (this.centerField.innerWidth() / 2));
this.rightField.css("left", width * 0.75 - (this.rightField.innerWidth() / 2));
this.firstBase.css("left", width * 0.65 - (this.firstBase.innerWidth() / 2));
this.secondBase.css("left", width * 0.58 - (this.secondBase.innerWidth() / 2));
this.thirdBase.css("left", width * 0.34 - (this.thirdBase.innerWidth() / 2));
this.shortstop.css("left", width * 0.4 - (this.shortstop.innerWidth() / 2));
this.pitcher.css("left", width * 0.5 - (this.pitcher.innerWidth() / 2));
this.catcher.css("left", width * 0.5 - (this.catcher.innerWidth() / 2));
};
Field.prototype.isRunning = function() {
return this.htsRunning || this.httRunning || this.fttRunning || this.hthRunning || this.fthRunning || this.sthRunning || this.tthRunning || this.sttRunning || this.ftsRunning || this.htfRunning;
};
Field.prototype.setBaserunners = function(runners) {
this.baserunners = runners;
};
Field.prototype.showBaserunners = function() {
var i, runner, _len, _ref;
if (this.showingBaserunners) {
_ref = this.baserunners;
for (i = 0, _len = _ref.length; i < _len; i++) {
runner = _ref[i];
if (!this.isEmptyObject(runner)) {
this.$baserunners[i].find("span").show();
} else {
this.$baserunners[i].find("span").hide();
}
}
}
};
Field.prototype.hideBaserunners = function() {
var base, _i, _len, _ref;
_ref = this.$baserunners;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
base = _ref[_i];
base.find("span").hide();
}
};
Field.prototype.toggleBaserunners = function() {
this.showingBaserunners = !this.showingBaserunners;
if (!this.showingBaserunners) {
this.hideBaserunners();
$("#toggle-baserunners").removeClass("on round-btn-small-on").addClass("round-btn-small").text(espn.gamecast.translate("BASERUNNERS OFF"));
} else {
if (this.showingSprayChart) {
this.toggleSprayChart();
}
if (this.showingDefense) {
this.toggleDefense();
}
this.showBaserunners();
$("#toggle-baserunners").removeClass("round-btn-small").addClass("on round-btn-small-on").text(espn.gamecast.translate("BASERUNNERS ON"));
}
};
Field.prototype.handleResize = function(opts) {
if (!opts) {
return;
}
this.removeMarks();
this.isAnimating = false;
if (opts.width && opts.height) {
$("#" + opts.canvasId).attr({
width: opts.width,
height: opts.height
});
this.size = {
width: opts.width,
height: opts.height
};
}
this.keanu.reset();
this.keanu = null;
this.keanu = new Keanu(opts.canvasId || "field-render");
if (this.showingSprayChart) {
this.showingSprayChart = false;
this.toggleSprayChart();
} else {
if (this.showingDefense) {
this.showingDefense = false;
this.toggleDefense();
} else {
if (this.showingBaserunners) {
this.showingBaserunners = false;
this.toggleBaserunners();
}
}
}
};
Field.prototype.reset = function() {
this.keanu.reset();
this.setBaserunners([0, 0, 0]);
this.removeMarks();
this.pitchQueue = [];
this.showingBaserunners = true;
if (this.showingSprayChart) {
this.toggleSprayChart();
}
if (this.showingDefense) {
this.toggleDefense();
}
this.showBaserunners();
this.showingSprayChart = false;
this.showingDefense = false;
this.isAnimating = false;
this.sprayChart = {
outLeftPct: 0,
outMidPct: 0,
outRightPct: 0,
infLeftPct: 0,
infMidPct: 0,
infRightPct: 0
};
$("#toggle-baserunners").removeClass("round-btn-small").addClass("on round-btn-small-on").text(espn.gamecast.translate("BASERUNNERS ON"));
};
return Field;
})();
espn.gamecast.field = Field;
})(jQuery);
}).call(this);
espn.gamecast.baserunners = {};
(function($) {
var RUNNERS = espn.gamecast.baserunners,
field = null,
$baserunners = [$("#br-1"), $("#br-2"), $("#br-3")],
baserunners = [],
differences = [],
cache = {},
team = "",
score = 0,
outs = 0,
scoringPlay = false,
isEmpty = espn.gamecast.isEmptyObject,
firstOnMap = [],
scoreMap = [];
RUNNERS.init = function(data) {
espn.gamecast.debug("Init runners");
espn.gamecast.debug(data);
baserunners = data.runners;
field = data.field ? data.field : field;
team = data.team;
score = data.score;
outs = data.outs;
cache = {};
firstOnMap = [field.homeToFirst, field.homeToSecond, field.homeToThird];
scoreMap = [field.firstToHome, field.secondToHome, field.thirdToHome];
RUNNERS.showBases();
};
RUNNERS.update = function(data) {
if (!data) {
return;
}
var dScore = parseInt(data.score, 10),
scoreDiff = dScore - score,
dOuts = parseInt(data.outs, 10),
outDiff = dOuts - outs,
i;
espn.gamecast.debug("Old score: " + score + ", New score: " + dScore);
if (outDiff > 0 || scoreDiff > 0 || RUNNERS.hasRunners(data.runners)) {
if (dOuts >= 3) {
RUNNERS.reset();
} else {
if (data.team == team) {
RUNNERS.hideBases();
if (data.eventType && (data.eventType == 28 || data.eventType == 30)) {
RUNNERS.score();
field.homeToHome();
} else {
var minBase = 0,
hitMap = ["First", "Second", "Third"];
espn.gamecast.debug(data.runners);
for (i = 0; i < 3; i += 1) {
espn.gamecast.debug(data.runners[i]);
if (data.runners[i] && data.runners[i].id > 0 && RUNNERS.getBase(data.runners[i].id, baserunners, "prev") < 0) {
espn.gamecast.debug("First on.. " + i);
firstOnMap[i] && firstOnMap[i].call(field);
minBase = i;
break;
}
}
if (scoreDiff > 0) {
RUNNERS.score(2, 2 - scoreDiff);
}
for (i = 3 - scoreDiff; i > 0; i -= 1) {
if (data.runners[i] && RUNNERS.getBase(data.runners[i].id, baserunners, "prev") >= 0) {
if (RUNNERS.getBase(data.runners[i].id, data.runners, "cur") >= 0) {
if (RUNNERS.getBase(data.runners[i].id, baserunners, "prev") != RUNNERS.getBase(data.runners[i].id, data.runners, "cur")) {
field[hitMap[RUNNERS.getBase(data.runners[i].id, baserunners, "prev")].toLowerCase() + "To" + hitMap[RUNNERS.getBase(data.runners[i].id, data.runners, "cur")]](function() {
RUNNERS.showBase(i);
});
}
} else {
espn.gamecast.debug("Someone is out");
if (RUNNERS.getBase(data.runners[i].id, baserunners, "prev") <= minBase) {
field[hitMap[RUNNERS.getBase(data.runners[i].id, baserunners, "prev")].toLowerCase() + "To" + hitMap[RUNNERS.getBase(data.runners[i].id, baserunners, "prev") + (minBase + 1)]](function() {
RUNNERS.showBase(i);
});
} else {
field[hitMap[RUNNERS.getBase(data.runners[i].id, baserunners, "prev")].toLowerCase() + "To" + hitMap[RUNNERS.getBase(data.runners[i].id, baserunners, "prev") + 1]](function() {
RUNNERS.showBase(i);
});
}
}
}
}
var fn = function() {
if (field.isRunning()) {
setTimeout(fn, 50);
} else {
RUNNERS.init(data);
}
};
setTimeout(fn, 250);
}
} else {
if (data.team != team) {
RUNNERS.init(data);
}
}
}
}
};
RUNNERS.hasRunners = function(runners) {
espn.gamecast.debug("Has Runners?");
var test = false;
for (var i = 0; i < 3; i += 1) {
if (baserunners[i] && runners[i]) {
if (baserunners[i].id != runners[i].id) {
test = true;
break;
}
} else {
if ((runners[i] && !baserunners[i]) || (baserunners[i] && !runners[i])) {
test = true;
break;
}
}
}
espn.gamecast.debug(test);
return test;
};
RUNNERS.score = function(start, end) {
espn.gamecast.debug("Score!");
start = start || 0;
end = end || 3;
if (start < end) {
for (; start < end; start += 1) {
if (baserunners[start] && baserunners[start].id > 0) {
scoreMap[start] && scoreMap[start].call(field);
}
}
} else {
espn.gamecast.debug(start + " " + end);
for (; start > end; start -= 1) {
if (baserunners[start] && baserunners[start].id > 0) {
scoreMap[start] && scoreMap[start].call(field);
}
}
}
};
RUNNERS.getBase = function(id, runners, co) {
var base = -1;
if (id) {
if (typeof cache[co + "" + id] != "undefined") {
espn.gamecast.debug("Using cached value for key " + co + "" + id + " : " + cache[co + "" + id]);
base = cache[co + "" + id];
} else {
for (var i = 0; i < 3; i += 1) {
if (runners[i] && runners[i].id == id) {
base = i;
cache[co + "" + id] = i;
break;
}
}
}
}
return base;
};
RUNNERS.reset = function() {
cache = {};
team = "";
score = 0;
outs = 0;
baserunners = [{}, {}, {}];
RUNNERS.hideBases();
};
RUNNERS.showBase = function(base) {
if (base && base < 3 && base >= 0) {
$baserunners[base].show();
}
};
RUNNERS.showBases = function() {
for (var b = 0, l = baserunners.length; b < l; b += 1) {
if (baserunners[b] && !isEmpty(baserunners[b]) && baserunners[b].id > 0) {
$baserunners[b].attr({
"data-playerId": baserunners[b].id,
"data-position": "R",
href: espn.gamecast.getPlayerLinkHREF(baserunners[b].id)
}).find("span").text(baserunners[b].lastName).end().show();
} else {
$baserunners[b].hide();
}
}
field.showBaserunners();
};
RUNNERS.hideBases = function() {
for (var b = 0, l = $baserunners.length; b < l; b += 1) {
$baserunners[b].hide();
}
};
}(jQuery));
espn = espn || {};
espn.gamecast = espn.gamecast || {};
espn.gamecast.pitchZone = {};
(function($) {
var ZONE = espn.gamecast.pitchZone,
batAvg = 0,
pitches = [],
avgs = [],
alphas = [],
zones = [],
$grid = $("#pitch-zone-grid"),
$stance = $("#pitch-zone-stance"),
gridW = $grid.width() || 124,
gridH = $grid.height() || 124,
rgb = {
cold: "54, 98, 171",
hot: "214,33,40"
},
hex = {
hot: "860000",
cold: "004C80"
},
heatMapOn = false,
velTypeOn = false,
dimension = 22,
transformX = function(x) {
var newX = ((x - 43) * 1.13) - (dimension / 2);
if (newX < 0) {
newX = 0;
}
if (newX > gridW) {
newX = gridW;
}
return newX;
},
transformY = function(y) {
var newY = ((y - 78) * 1.1) - (dimension / 2);
if (newY < 0) {
newY = 0;
}
if (newY > gridH) {
newY = gridH;
}
return newY;
},
getAlpha = function(avg) {
alpha = Math.abs((avg - batAvg) / batAvg);
if (alpha < 0.8) {
alpha += 0.1;
}
return alpha.toFixed(2);
},
getIEAlphaHex = function(a) {
var h = Math.floor(a * 255).toString(16);
return "00".slice(h.length) + h;
};
ZONE.init = function(data) {
batAvg = 0.3;
avgs = data.averages || 0;
pitches = data.pitches || [];
stance = data.stance || "";
ZONE.setBattingStance(stance);
ZONE.setAverages(avgs);
if (pitches.length > 0) {
ZONE.replayPitches();
}
};
ZONE.setBattingStance = function(stance) {
$stance.show().get(0).className = "batter-stance " + stance;
};
ZONE.setBattingAverage = function(avg) {
batAvg = avg < 0 ? 0 : avg;
};
ZONE.setAverages = function(data) {
avgs = Array.apply(null, data);
avgs.reverse();
for (var i = 0, len = avgs.length; i < len; i += 1) {
if (avgs != "") {
alphas[i] = avgs[i] == -1 ? 0 : getAlpha(avgs[i]);
zones[i] = avgs[i] >= batAvg ? "hot" : "cold";
}
}
ZONE.adjustHeatMap();
};
ZONE.adjustHeatMap = function() {
$grid.find(".pz-quadrant").each(function(i) {
try {
$(this).css({
"background-color": "transparent",
"background-color": "rgba(" + rgb[zones[i]] + ", " + alphas[i] + ")"
}).find(".avg").text(avgs[i] == -1 ? "" : avgs[i]);
} catch (e) {}
});
};
ZONE.showHeatMap = function() {
if (!heatMapOn) {
$grid.addClass("heat-map-on");
$grid.find(".pitch").hide();
if (zones.length === 0) {
$grid.find(".avg").hide();
} else {
$grid.find(".avg").css("display", "block");
}
}
};
ZONE.hideHeatMap = function() {
if (heatMapOn) {
$grid.removeClass("heat-map-on");
$grid.find(".pitch").show();
$grid.find(".avg").hide();
}
};
ZONE.showVelType = function() {
$(".pitch-vel-type,.pitch-zone-mobile").addClass("show");
setTimeout(function() {
$(".pitch-zone-mobile").removeClass("show");
}, 3000);
};
ZONE.hideVelType = function() {
$(".pitch-vel-type").removeClass("show");
};
ZONE.toggleHeatMap = function() {
if (heatMapOn) {
ZONE.hideHeatMap();
$("#toggle-heat-map").removeClass("on").text(espn.gamecast.translate("HIT ZONE OFF"));
} else {
ZONE.showHeatMap();
$("#toggle-heat-map").addClass("on").text(espn.gamecast.translate("HIT ZONE ON"));
}
heatMapOn = !heatMapOn;
};
ZONE.pitch = function(data, replay) {
var x = transformX(data.x) || 0,
y = transformY(data.y) || 0,
type = data.type || "strike",
pitch = data.pitch || pitches.length + 1,
vel = data.vel,
replay = replay || false;
if (!replay) {
pitches.push({
x: x,
y: y,
type: type,
pitch: pitch,
vel: vel
});
}
if (heatMapOn) {
$('<div class="pitch ' + type + '" style="display: none; left:' + x + "px; top: " + y + 'px;">' + pitch + "</div>").appendTo("#pitch-zone-grid");
} else {
$('<div class="pitch ' + type + '" style="display: none; left:' + x + "px; top: " + y + 'px;">' + pitch + "</div>").appendTo("#pitch-zone-grid").fadeIn();
}
};
ZONE.setVelType = function(data) {
var vel = data.vel;
if (vel !== undefined && vel != "") {
$(".pitch-vel-type span.pitchinfo,.pitch-zone-mobile").html(vel);
ZONE.showVelType();
} else {
ZONE.hideVelType();
}
};
ZONE.replayPitches = function() {
for (var i = 0, l = pitches.length; i < l; i += 1) {
ZONE.pitch(pitches[i], true);
ZONE.setVelType(pitches[i]);
}
};
ZONE.reset = function() {
$grid.find(".pitch").remove();
$stance.hide().get(0).className = "batting-stance";
pitches = [];
avgs = [];
alphas = [];
zones = [];
ZONE.hideVelType();
};
ZONE.thereIsNoCryingInBaseball = function() {
return pitches;
};
}(jQuery));
espn.gamecast.pitchInfo = {};
(function($) {
var INFO = espn.gamecast.pitchInfo,
pitches = [],
$list = $("#pitch-info-list");
INFO.init = function(data) {
pitches = data;
if (pitches.length > 0) {
INFO.replayPitches();
}
};
INFO.reset = function() {
pitches = [];
$list.html("");
$(".pitch-vel-type,.pitch-zone-mobile").removeClass("show");
};
INFO.pitch = function(data) {
var pitch = data.pitch || pitches.length + 1,
result = data.result || "",
lowerRes = result.toLowerCase(),
cssClass = "";
pitches.push({
pitch: pitch,
result: result
});
$list.prepend('<li><div class="' + INFO.getPitchClass(result) + '">' + pitch + "</div><p>" + result + "</p></li>");
};
INFO.replayPitches = function() {
var pitchHtml = "";
for (var i = pitches.length - 1; i >= 0; i -= 1) {
pitchHtml += '<li><div class="' + INFO.getPitchClass(pitches[i].result) + '">' + pitches[i].pitch + "</div><p>" + pitches[i].result + "</p></li>";
}
$list.html(pitchHtml);
};
INFO.getPitchClass = function(text) {
text = text.toLowerCase() || "";
var cssClass = "";
if (text.indexOf("strike") >= 0) {
cssClass = "strike";
} else {
if (text.indexOf("foul") >= 0) {
cssClass = "foul";
} else {
if (text.indexOf("ball") >= 0 || text.indexOf("bola") >= 0) {
cssClass = "ball";
} else {
if (text.indexOf("in play") >= 0 || text.toLowerCase().indexOf("en juego") >= 0) {
cssClass = "play";
}
}
}
}
return cssClass;
};
INFO.getPitches = function() {
return pitches;
};
}(jQuery));
espn.gamecast.bvp = {};
(function($) {
var BVP = espn.gamecast.bvp,
$pitcher = $("#bvp-pitcher"),
$batter = $("#bvp-batter"),
pitchingTeam = "",
battingTeam = "",
pitchingHand = "",
battingHand = "",
lastPitcher = 0,
lastBatter = 0,
pitchStatIndex = 0,
batStatIndex = 0,
pitcherInterval = null,
batterInterval = null,
dataCount = 0,
pitcherPos = "",
isHandset = !!(espn.gamecast.version && espn.gamecast.version.isHandset());
BVP.reset = function() {
espn.gamecast.debug("Resetting BVP");
BVP.update({
pitcher: false,
batter: false
});
lastPitcher = 0;
lastBatter = 0;
pitchStatIndex = 0;
batStatIndex = 0;
dataCount = 0;
clearInterval(batterInterval);
batterInterval = null;
};
BVP.update = function(data) {
var pitcher = data.pitcher,
batter = data.batter;
BVP.updatePitcher(pitcher);
BVP.updateBatter(batter);
BVP.autoScroll();
};
BVP.updatePitcher = function(data) {
if (data && !espn.gamecast.isEmptyObject(data)) {
var html = "",
fade = true,
isStarter = data.isStarter == "true",
showSeason = false;
if (lastPitcher == 0) {
lastPitcher = data.id;
} else {
if (lastPitcher != data.id) {
pitchStatIndex = 0;
lastPitcher = data.id;
} else {
if (lastPitcher == data.id) {
fade = false;
}
}
}
dataCount = 0;
extra = "";
pitchingTeam = data.team || "";
html = '<div class="stat-scroller"> > </div>';
html += '<div style="z-index:5" class="bvp-player-photo">';
html += '<img src="http://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/' + data.id + '.png&w=120&h=90&scale=crop&background=0XCCCCCC&transparent=true" />';
html += "</div>";
if (!espn.gamecast.master.current.isAllStarGame) {
html += '<img class="team-logo" src="http://a2.espncdn.com/prod/assets/clubhouses/2010/mlb/logos/' + data.team + '.png">';
}
html += '<div class="bvp-player-info">';
html += '<h2><a href="' + espn.gamecast.getPlayerLinkHREF(data.id) + '" class="poppable" data-playerId="' + data.id + '" data-position="P">' + (isHandset ? data.firstName.substring(0, 1) + "." : data.firstName) + " <span>" + data.lastName + "</span></a></h2>";
html += '<p class="pos-number">';
if (typeof data.hand != "undefined") {
pitchingHand = data.hand || "";
pitcherPos = data.hand + "H";
}
pitcherPos += data.position;
html += espn.gamecast.translate(pitcherPos);
if (typeof data.number != "undefined") {
html += " #" + data.number;
}
html += "</p>";
html += '<div id="pitcher-stat-swap">';
if (data.today) {
if (dataCount == pitchStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("TODAY") + "</p>";
html += '<p class="stat-line">' + (BVP.getValue(data.today.inningsPitched) || 0) + " " + espn.gamecast.translate("IP") + ", " + BVP.getValue(data.today.er) + " " + espn.gamecast.translate("ER");
if (BVP.hasValue(data.today.strikeouts)) {
html += ", " + BVP.getValue(data.today.strikeouts) + " " + espn.gamecast.translate("SO");
}
if (BVP.hasValue(data.today.walks)) {
html += ", " + BVP.getValue(data.today.walks) + " " + espn.gamecast.translate("BB");
}
html += "</p></div>";
dataCount++;
}
if (data.season && BVP.hasValue(data.season.innings)) {
showSeason = true;
if (dataCount == pitchStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("SEASON") + "</p>";
html += '<p class="stat-line">';
if (isStarter) {
html += (data.season.wins || 0) + "-" + (data.season.losses || 0) + ", ";
} else {
html += (data.season.saves || 0) + " " + espn.gamecast.translate("SV") + ", " + (data.season.holds || 0) + " " + espn.gamecast.translate("HLD") + ", ";
}
html += (data.season.era || 0) + " " + espn.gamecast.translate("ERA") + ", " + BVP.getValue(data.season.strikeouts) + " " + espn.gamecast.translate("SO");
html += "</p>";
html += "</div>";
dataCount++;
}
if (data.lastSeason && BVP.hasValue(data.lastSeason.innings) && (!showSeason || (showSeason && data.season.innings < 10))) {
if (dataCount == pitchStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("LAST SEASON") + "</p>";
html += '<p class="stat-line">';
if (isStarter) {
html += (data.lastSeason.wins || 0) + "-" + (data.lastSeason.losses || 0) + ", ";
} else {
html += (data.lastSeason.saves || 0) + " " + espn.gamecast.translate("SV") + ", " + (data.lastSeason.holds || 0) + " " + espn.gamecast.translate("HLD") + ", ";
}
html += (data.lastSeason.era || 0) + " " + espn.gamecast.translate("ERA") + ", " + BVP.getValue(data.lastSeason.strikeouts) + " " + espn.gamecast.translate("SO");
html += "</p>";
html += "</div>";
dataCount++;
}
if (data.vsLH && battingHand != "R") {
if (dataCount == pitchStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("vs LH") + "</p>";
html += '<p class="stat-line">' + (BVP.getValue(data.vsLH.battersFaced) || 0) + " " + espn.gamecast.translate("TBF") + ", " + (BVP.getValue(data.vsLH.oppAvg) || 0) + " " + espn.gamecast.translate("BA") + ", " + BVP.getValue(data.vsLH.strikeouts) + " " + espn.gamecast.translate("SO") + "</p>";
html += "</div>";
dataCount++;
}
if (data.vsRH && battingHand != "L") {
if (dataCount == pitchStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("vs RH") + "</p>";
html += '<p class="stat-line">' + (BVP.getValue(data.vsRH.battersFaced) || 0) + " " + espn.gamecast.translate("TBF") + ", " + (BVP.getValue(data.vsRH.oppAvg) || 0) + " " + espn.gamecast.translate("BA") + ", " + BVP.getValue(data.vsRH.strikeouts) + " " + espn.gamecast.translate("SO") + "</p>";
html += "</div>";
dataCount++;
}
html += "</div>";
html += '<p class="misc">' + espn.gamecast.translate("PITCH COUNT") + ": " + data.today.pitches + "</p>";
html += "</div>";
if (fade) {
$pitcher.fadeOut(250, function() {
$(this).css("border-color", (data.teamColor || "")).html(html).fadeIn(250);
});
} else {
$pitcher.css("border-color", (data.teamColor || "")).html(html);
}
BVP.autoScroll();
} else {
$pitcher.html("");
}
};
BVP.updateBatter = function(data) {
if (data && !espn.gamecast.isEmptyObject(data)) {
if (data.id > 0) {
var html = "",
fade = true,
showSeason = false;
if (lastBatter == 0) {
lastBatter = data.id;
} else {
if (lastBatter != data.id) {
batStatIndex = 0;
lastBatter = data.id;
} else {
if (lastBatter == data.id) {
fade = false;
}
}
}
battingHand = data.bats || "";
battingTeam = data.team || "";
dataCount = 0;
html = '<div class="stat-scroller"> > </div>';
html += '<div class="bvp-player-photo">';
html += '<img src="http://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/' + data.id + '.png&w=120&h=90&scale=crop&background=0XCCCCCC&transparent=true" />';
html += "</div>";
if (!espn.gamecast.master.current.isAllStarGame) {
html += '<img class="team-logo" src="http://a2.espncdn.com/prod/assets/clubhouses/2010/mlb/logos/' + data.team + '.png">';
}
html += '<div class="bvp-player-info">';
html += '<h2><a href="' + espn.gamecast.getPlayerLinkHREF(data.id) + '" class="poppable" data-playerId="' + data.id + '" data-position="R">' + (isHandset ? data.firstName.substring(0, 1) + "." : data.firstName) + " <span>" + data.lastName + "</span></a></h2>";
html += '<p class="pos-number">' + espn.gamecast.translate(data.position);
if (data.number != undefined) {
html += " #" + data.number;
}
html += "</p>";
html += '<div id="batter-stat-swap">';
if (data.today) {
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("TODAY") + "</p>";
if (BVP.hasValue(data.today.atBats) || BVP.hasValue(data.today.walks) || BVP.hasValue(data.today.RBIs)) {
html += '<p class="stat-line">' + data.today.hits + "-" + data.today.atBats;
if (BVP.hasValue(data.today.runs)) {
html += ", " + BVP.getValue(data.today.runs) + " " + espn.gamecast.translate("R");
}
if (BVP.hasValue(data.today.RBIs)) {
html += ", " + BVP.getValue(data.today.RBIs) + " " + espn.gamecast.translate("RBI");
}
if (BVP.hasValue(data.today.walks)) {
html += ", " + BVP.getValue(data.today.walks) + " " + espn.gamecast.translate("BB");
}
if (BVP.hasValue(data.today.strikeouts)) {
html += ", " + BVP.getValue(data.today.strikeouts) + " " + espn.gamecast.translate("SO");
}
html += "</p>";
} else {
html += '<p class="stat-line">' + espn.gamecast.translate("First At Bat") + "</p>";
}
html += "</div>";
dataCount++;
}
if (data.season && BVP.hasValue(data.season.atBats)) {
showSeason = true;
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + (espn.gamecast.master.current.seasonType == 3 ? espn.gamecast.translate("SERIES") : espn.gamecast.translate("SEASON")) + "</p>";
html += '<p class="stat-line">' + (data.season.avg) + ", " + BVP.getValue(data.season.RBIs) + " " + espn.gamecast.translate("RBI") + ", " + BVP.getValue(data.season.homeRuns) + " " + espn.gamecast.translate("HR") + "</p>";
html += "</div>";
dataCount++;
}
if (data.lastSeason && BVP.hasValue(data.lastSeason.atBats) && (!showSeason || (showSeason && data.season.atBats < 10))) {
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("LAST SEASON") + "</p>";
html += '<p class="stat-line">' + (data.lastSeason.avg) + ", " + BVP.getValue(data.lastSeason.RBIs) + " " + espn.gamecast.translate("RBI") + ", " + BVP.getValue(data.lastSeason.homeRuns) + " " + espn.gamecast.translate("HR") + "</p>";
html += "</div>";
dataCount++;
}
if (data.vsOpp && BVP.hasValue(data.vsOpp.atBats)) {
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
var teamName = pitchingTeam == "" ? espn.gamecast.translate("Opponent") : pitchingTeam.toUpperCase();
html += '<p class="heading">' + espn.gamecast.translate("vs") + " " + teamName + "</p>";
html += '<p class="stat-line">' + (data.vsOpp.avg || 0) + ", " + BVP.getValue(data.vsOpp.RBIs) + " " + espn.gamecast.translate("RBI") + ", " + BVP.getValue(data.vsOpp.homeRuns) + " " + espn.gamecast.translate("HR") + "</p>";
html += "</div>";
dataCount++;
}
if (data.vsLH && pitchingHand == "L") {
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("vs LHP") + "</p>";
if (BVP.hasValue(data.vsLH.atBats)) {
html += '<p class="stat-line">' + (BVP.getValue(data.vsLH.avg) || 0) + ", " + BVP.getValue(data.vsLH.RBIs) + " " + espn.gamecast.translate("RBI") + ", " + BVP.getValue(data.vsLH.homeRuns) + " " + espn.gamecast.translate("HR") + "</p>";
} else {
html += '<p class="stat-line">' + espn.gamecast.translate("No stats available") + "</p>";
}
html += "</div>";
dataCount++;
}
if (data.vsRH && pitchingHand == "R") {
if (dataCount == batStatIndex) {
html += '<div class="swappable-stat-line shown">';
} else {
html += '<div class="swappable-stat-line" style="display: none">';
}
html += '<p class="heading">' + espn.gamecast.translate("vs RHP") + "</p>";
if (BVP.hasValue(data.vsRH.atBats)) {
html += '<p class="stat-line">' + (BVP.getValue(data.vsRH.avg) || 0) + ", " + BVP.getValue(data.vsRH.RBIs) + " " + espn.gamecast.translate("RBI") + ", " + BVP.getValue(data.vsRH.homeRuns) + " " + espn.gamecast.translate("HR") + "</p>";
} else {
html += '<p class="stat-line">' + espn.gamecast.translate("No stats available") + "</p>";
}
html += "</div>";
dataCount++;
}
html += "</div>";
html += "</div>";
if (fade) {
$batter.fadeOut(250, function() {
$(this).css("border-color", (data.teamColor || "")).html(html).fadeIn(250);
});
} else {
$batter.css("border-color", (data.teamColor || "")).html(html);
}
}
BVP.autoScroll();
} else {
$batter.html("");
}
};
BVP.hasValue = function(stat) {
return (stat != "-" && stat > 0);
};
BVP.getValue = function(stat) {
return stat == "-" ? 0 : (stat === "1" ? "" : stat);
};
BVP.autoScroll = function() {
var scroll = function() {
if ($("#inning-view").css("display") == "block") {
BVP.scroll("#bvp-pitcher .stat-scroller");
BVP.scroll("#bvp-batter .stat-scroller");
}
};
if (!batterInterval) {
batterInterval = setInterval(scroll, 10000);
}
};
BVP.scroll = function(das) {
var isEvent = das.currentTarget || false,
$siblings = $(das).siblings(".bvp-player-info"),
$stats = $siblings.length > 0 ? $siblings.find(".swappable-stat-line") : [],
len = $stats.length,
$this, html = "",
index = -1;
if (len > 0) {
$stats.each(function(i) {
$this = $(this);
if ($this.hasClass("shown")) {
$this.fadeOut(250, function() {
$this.removeClass("shown").hide();
if ($this.is(".swappable-stat-line:last-child")) {
try {
$this.siblings(".swappable-stat-line:first-child").addClass("shown").fadeIn(250);
} catch (e) {}
if ($this.parents("#bvp-pitcher").length > 0) {
pitchStatIndex = 0;
} else {
batStatIndex = 0;
}
} else {
$this.next(".swappable-stat-line").addClass("shown").fadeIn(250);
if ($this.parents("#bvp-pitcher").length > 0) {
pitchStatIndex = i + 1;
} else {
batStatIndex = i + 1;
}
}
});
return false;
}
});
}
};
}(jQuery));
espn.gamecast.playerCard = {};
(function($) {
var CARD = espn.gamecast.playerCard,
debug = espn.gamecast.debug,
$card = $("#player-pop-card"),
$arrow = $("#player-pop-arrow"),
cache = {},
useCache = false,
gameId = -1,
lang = settings.lang;
$card.prependTo("body");
$arrow.prependTo("body");
$card.delegate("#player-pop-close", "click", function(e) {
e.preventDefault();
CARD.hide();
});
CARD.init = function(data) {
cache = data.cache || {};
useCache = data.useCache || false;
if (!useCache) {
CARD.clearCache();
}
};
CARD.show = function(e) {
if ($card.length > 0) {
e.preventDefault();
var html = "",
$this = $(this),
offset = $this.offset(),
playerId = $this.attr("data-playerId"),
position = $this.attr("data-position"),
deportes = settings.lang == "es" ? "/deportes" : "",
url = position.toLowerCase() == "p" ? "/mlb" + deportes + "/gamecast12/util/getPitcherCard" : "/mlb" + deportes + "/gamecast12/util/getBatterCard",
gameId = espn.gamecast.master.current.id,
loadCard = function() {
$card.html(html).css("display", "block");
$arrow.css("display", "block");
var top = offset.top - $arrow.height() - ($card.outerHeight() / 1.5) < 0 ? false : true,
left = offset.left + $arrow.width() + $card.outerWidth() + $this.outerWidth() > $(window).width() ? true : false,
arrowClass, arrowX, arrowY, cardClass, cardX, cardY;
if (left) {
arrowClass = top ? "br" : "tr";
cardClass = "left";
} else {
arrowClass = top ? "bl" : "tl";
cardClass = "right";
}
arrowX = left ? offset.left - $arrow.width() : offset.left + $this.outerWidth();
arrowY = top ? offset.top - $arrow.height() : offset.top + $this.outerHeight();
cardX = left ? arrowX - $card.outerWidth() : arrowX + $arrow.width();
cardY = top ? arrowY - ($card.outerHeight() / 1.5) : arrowY - ($card.outerHeight() / 5);
var cardCSS = {},
arrowCSS = {};
if ($(window).width() <= 926) {
cardCSS.top = Math.max(cardY, 0); + "px";
cardCSS.left = "50%";
cardCSS.marginLeft = "-149px";
arrowCSS.display = "none";
} else {
cardCSS.top = cardY + "px";
cardCSS.left = cardX + "px";
cardCSS.marginLeft = "auto";
arrowCSS.display = "block";
arrowCSS.top = arrowY + "px";
arrowCSS.left = arrowX + "px";
}
$arrow.css(arrowCSS).removeClass().addClass("pop-arrow " + arrowClass);
$card.css(cardCSS).removeClass().addClass("player-card-pop " + cardClass);
};
if (useCache) {
if (cache[playerId]) {
html = cache[playerId];
loadCard();
} else {
$.ajax({
url: url,
data: {
playerId: playerId,
gameId: gameId,
lang: lang
},
success: function(d) {
cache[playerId] = d;
html = d;
loadCard();
}
});
}
} else {
$.ajax({
url: url,
data: {
playerId: playerId,
gameId: gameId,
lang: lang
},
success: function(d) {
html = d;
loadCard();
}
});
}
} else {
return true;
}
};
CARD.hide = function() {
$arrow.hide();
$card.hide();
$card.html("");
};
CARD.clearCache = function() {
cache = {};
};
CARD.getCache = function() {
return cache;
};
}(jQuery));
espn.gamecast.boxScore = {};
(function($) {
var BOX = espn.gamecast.boxScore,
$teams = {
away: $("#box-score-away"),
home: $("#box-score-home")
};
BOX.updateHome = function(data) {
BOX.update("home", {
home: data
});
};
BOX.updateAway = function(data) {
BOX.update("away", {
away: data
});
};
BOX.updateAll = function(data) {
BOX.update("home", data);
BOX.update("away", data);
};
BOX.update = function(team, data) {
var stats = data[team],
hitters = stats.hitters,
pitchers = stats.pitchers,
expandedBatting = stats.expandedBatting,
expandedPitching = stats.expandedPitching,
$team = $teams[team],
hitterHTML = "",
pitcherHTML = "",
expandedHTML = "",
expitchHTML = "",
current = "",
extra = "",
cssClass = "oddrow";
$team.find(".box-header").css("border-bottom", "2px solid " + stats.color).text(stats.team);
$(hitters).each(function() {
extra = (current == this.batOrder) ? " - " : "";
current = this.batOrder;
hitterHTML += '<tr class="' + cssClass + '">';
hitterHTML += '<td class="hc left">' + extra + '<a href="' + espn.gamecast.getPlayerLinkHREF(this.id) + '" class="poppable" data-playerid="' + this.id + '" data-position="B">' + this.firstName.substr(0, 1) + ". " + this.lastName + ' <span class="pos">' + this.position + "</span></a></td>";
hitterHTML += "<td>" + this.today.atBats + "</td>";
hitterHTML += "<td>" + this.today.runs + "</td>";
hitterHTML += "<td>" + this.today.hits + "</td>";
hitterHTML += "<td>" + this.today.RBIs + "</td>";
hitterHTML += "<td>" + this.today.walks + "</td>";
hitterHTML += "<td>" + this.today.strikeouts + "</td>";
hitterHTML += "<td>" + this.today.avg + "</td>";
hitterHTML += "</tr>";
cssClass = cssClass == "oddrow" ? "evenrow" : "oddrow";
});
var dlen = expandedBatting["2B"].length,
tlen = expandedBatting["3B"].length,
hrlen = expandedBatting.HR.length,
sblen = expandedBatting.SB.length;
if (dlen > 0 || tlen > 0 || hrlen > 0 || sblen > 0) {
expandedHTML = "<ul>";
if (dlen > 0) {
expandedHTML += "<li>";
expandedHTML += "<b>" + espn.gamecast.translate("2B") + ":</b> ";
$(expandedBatting["2B"]).each(function(i) {
if (i > 0) {
expandedHTML += ", " + this.name + " ";
} else {
expandedHTML += this.name + " ";
}
if (this.today > 1) {
expandedHTML += this.today + " ";
}
if (this.season != "-" && !espn.gamecast.master.current.isAllStarGame) {
expandedHTML += "(" + this.season + ")";
}
});
expandedHTML += "</li>";
}
if (tlen > 0) {
expandedHTML += "<li>";
expandedHTML += "<b>" + espn.gamecast.translate("3B") + ":</b> ";
$(expandedBatting["3B"]).each(function(i) {
if (i > 0) {
expandedHTML += ", " + this.name + " ";
} else {
expandedHTML += this.name + " ";
}
if (this.today > 1) {
expandedHTML += this.today + " ";
}
if (this.season != "-" && !espn.gamecast.master.current.isAllStarGame) {
expandedHTML += "(" + this.season + ")";
}
});
expandedHTML += "</li>";
}
if (hrlen > 0) {
expandedHTML += "<li>";
expandedHTML += "<b>" + espn.gamecast.translate("HR") + ":</b> ";
$(expandedBatting.HR).each(function(i) {
if (i > 0) {
expandedHTML += ", " + this.name + " ";
} else {
expandedHTML += this.name + " ";
}
if (this.today > 1) {
expandedHTML += this.today + " ";
}
if (this.season != "-" && !espn.gamecast.master.current.isAllStarGame) {
expandedHTML += "(" + this.season + ")";
}
});
expandedHTML += "</li>";
}
if (sblen > 0) {
expandedHTML += "<li>";
expandedHTML += "<b>" + espn.gamecast.translate("SB") + ":</b> ";
$(expandedBatting.SB).each(function(i) {
if (i > 0) {
expandedHTML += ", " + this.name + " ";
} else {
expandedHTML += this.name + " ";
}
if (this.today > 1) {
expandedHTML += this.today + " ";
}
if (this.season != "-" && !espn.gamecast.master.current.isAllStarGame) {
expandedHTML += "(" + this.season + ")";
}
});
expandedHTML += "</li>";
}
expandedHTML += "</ul>";
} else {}
cssClass = "oddrow";
extra = "";
$(pitchers).each(function(i) {
if (i > 0) {
extra = " - ";
}
pitcherHTML += '<tr class="' + cssClass + '">';
pitcherHTML += '<td class="hc left">' + extra + '<a href="' + espn.gamecast.getPlayerLinkHREF(this.id) + '" class="poppable" data-playerid="' + this.id + '" data-position="P">' + this.firstName.substr(0, 1) + ". " + this.lastName + "</a>" + (this.note ? '<span class="note">' + this.note + "</span>" : "") + "</td>";
pitcherHTML += "<td>" + this.today.inningsPitched + "</td>";
pitcherHTML += "<td>" + this.today.hits + "</td>";
pitcherHTML += "<td>" + this.today.runs + "</td>";
pitcherHTML += "<td>" + this.today.er + "</td>";
pitcherHTML += "<td>" + this.today.walks + "</td>";
pitcherHTML += "<td>" + this.today.strikeouts + "</td>";
pitcherHTML += "<td>" + this.today.era + "</td>";
pitcherHTML += "</tr>";
cssClass = cssClass == "oddrow" ? "evenrow" : "oddrow";
});
var wplen = expandedPitching.WP.length,
ibblen = expandedPitching.IBB.length,
hbplen = expandedPitching.HBP.length,
blen = expandedPitching.B.length,
bflen = expandedPitching.BF.length,
gbfblen = expandedPitching.GBFB.length;
if (wplen > 0 || ibblen > 0 || hbplen > 0 || blen > 0 || bflen > 0 || gbfblen > 0) {
expitchHTML = "<ul>";
if (wplen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("WP") + ":</b> ";
$(expandedPitching.WP).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
if (ibblen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("IBB") + ":</b> ";
$(expandedPitching.IBB).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
if (hbplen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("HBP") + ":</b> ";
$(expandedPitching.HBP).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
if (blen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("Balk") + ":</b> ";
$(expandedPitching.B).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
if (bflen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("Batters Faced") + ":</b> ";
$(expandedPitching.BF).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
if (gbfblen > 0) {
expitchHTML += "<li>";
expitchHTML += "<b>" + espn.gamecast.translate("Ground Balls-Fly Balls") + ":</b> ";
$(expandedPitching.GBFB).each(function(i) {
if (i > 0) {
expitchHTML += ", " + this.name + " ";
} else {
expitchHTML += this.name + " ";
}
expitchHTML += this.today + " ";
});
expitchHTML += "</li>";
}
expitchHTML += "</ul>";
} else {}
$team.find(".box-score-hitter").html(hitterHTML).end().find(".expanded-batting").html(expandedHTML).end().find(".box-score-pitcher").html(pitcherHTML).end().find(".expanded-pitching").html(expitchHTML).end();
};
BOX.toggleExpandedStats = function(e) {
e.preventDefault();
$parent = $(this).parents(".box-footer");
$parent.children("div").slideToggle(250, function(e) {
$parent.toggleClass("expanded");
});
};
BOX.reset = function() {
$teams.away.find(".box-score-hitter").html("").end().find(".box-score-pitcher").html("").end();
$teams.home.find(".box-score-hitter").html("").end().find(".box-score-pitcher").html("").end();
};
}(jQuery));
espn.gamecast.gameStatus = {};
(function($) {
var STATUS = espn.gamecast.gameStatus,
isMobile = !!espn.gamecast.version,
isHandset = espn.gamecast.version && espn.gamecast.version.isHandset(),
$status = $("#game-status"),
$balls = $("#game-status-balls"),
$strikes = $("#game-status-strikes"),
$outs = $("#game-status-outs");
STATUS.update = function(data) {
var i, bHtml = "",
sHtml = "",
oHtml = "";
if (isHandset && data.gameState === "pregame") {
$status.find(".inning").html(STATUS.getPregameText(data));
} else {
$status.find(".inning").text(data.text.replace("de la", "") + " " + data.inning);
}
for (i = 1; i <= 4; i += 1) {
if (i <= data.balls) {
bHtml += '<div class="light ball"></div>';
} else {
bHtml += '<div class="light off"></div>';
}
}
for (i = 1; i <= 3; i += 1) {
if (i <= data.strikes) {
sHtml += '<div class="light strike"></div>';
} else {
sHtml += '<div class="light off"></div>';
}
}
for (i = 1; i <= 3; i += 1) {
if (i <= data.outs) {
oHtml += '<div class="light out"></div>';
} else {
oHtml += '<div class="light off"></div>';
}
}
$balls.html(bHtml);
$strikes.html(sHtml);
$outs.html(oHtml);
if (data.text.indexOf("Mid") >= 0 || data.text.indexOf("End") >= 0 || data.text.indexOf("Final") >= 0 || data.inning.indexOf("ET") >= 0 || data.text.indexOf("Fin ") >= 0 || data.text.indexOf("Mitad") >= 0) {
$status.addClass("downtime");
} else {
$status.removeClass("downtime");
}
};
STATUS.getPregameText = function(data) {
var outputHTML = STATUS.createDateText(data.gameDate) + "<br/>" + data.text.replace("de la", "") + " " + data.inning + '<div class="extra">' + data.seriesText + '<span class="tv">' + (data.tvText != "" && data.tvText != "&nbsp;" ? espn.gamecast.translate("TV") + ": " : "") + data.tvText + "</span></div>";
return outputHTML;
};
STATUS.createDateText = function(dateStr) {
var date = dateStr,
months = [espn.gamecast.translate("Jan"), espn.gamecast.translate("Feb"), espn.gamecast.translate("Mar"), espn.gamecast.translate("Apr"), espn.gamecast.translate("May"), espn.gamecast.translate("Jun"), espn.gamecast.translate("Jul"), espn.gamecast.translate("Aug"), espn.gamecast.translate("Sept"), espn.gamecast.translate("Oct"), espn.gamecast.translate("Nov"), espn.gamecast.translate("Dec")],
days = [espn.gamecast.translate("Sun"), espn.gamecast.translate("Mon"), espn.gamecast.translate("Tues"), espn.gamecast.translate("Wed"), espn.gamecast.translate("Thur"), espn.gamecast.translate("Fri"), espn.gamecast.translate("Sat")],
year, month, day;
if (dateStr && dateStr.length >= 8) {
year = parseInt(dateStr.substring(0, 4), 10);
month = parseInt(dateStr.substring(4, 6), 10) - 1;
day = parseInt(dateStr.substring(6), 10);
date = new Date(year, month, day);
return days[date.getDay()] + ", " + months[date.getMonth()] + " " + date.getDate();
} else {
return undefined;
}
};
STATUS.reset = function() {
STATUS.update({
text: "",
inning: "",
balls: 0,
strikes: 0,
outs: 0
});
};
}(jQuery));
espn.gamecast.dueUp = {};
(function($) {
var DUE = espn.gamecast.dueUp,
$dueUp = $("#due-up"),
$players = $dueUp.find(".bvp-player"),
emptyPlayer = {
id: "",
firstName: "",
lastName: "",
today: {},
season: {}
},
emptyTeam = {
name: "",
abbrev: "",
color: ""
};
DUE.reset = function() {
var data = {
players: [emptyPlayer, emptyPlayer, emptyPlayer],
inning: "",
team: emptyTeam,
dyk: ""
};
DUE.update(data);
};
DUE.getStat = function(stat) {
return stat == "-" ? 0 : (stat == 1 ? "" : stat);
};
DUE.update = function(data) {
var players = data.players && typeof data.players[0] !== "undefined" ? data.players : false,
inning = data.inning || "",
team = data.team || emptyTeam,
dyk = data.dyk || "",
stat = espn.gamecast.translate("TODAY");
if (players) {
$("#due-up > .heading").text(espn.gamecast.translate("Due up for the") + " " + team.name);
$players.each(function(i, v) {
stat = players[i].today.atBats == "-" || players[i].today.atBats == "0" ? "season" : "today";
var stats = "",
statCount = 0;
if (stat == "today") {
stats += (players[i][stat].hits || 0) + "-" + (players[i][stat].atBats || 0);
if (statCount < 3 && players[i][stat].homeRuns > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].homeRuns) + " " + espn.gamecast.translate("HR");
}
if (statCount < 3 && players[i][stat].RBIs > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].RBIs) + " " + espn.gamecast.translate("RBI");
}
if (statCount < 3 && players[i][stat].runs > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].runs) + " " + espn.gamecast.translate("R");
}
if (statCount < 3 && players[i][stat].walks > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].walks) + " " + espn.gamecast.translate("BB");
}
if (statCount < 3 && players[i][stat].stolenBases > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].stolenBases) + " " + espn.gamecast.translate("SB");
}
if (statCount < 3 && players[i][stat].strikeouts > 0) {
statCount++;
stats += ", " + DUE.getStat(players[i][stat].strikeouts) + " " + espn.gamecast.translate("SO");
}
} else {
stats += players[i][stat].avg != "-" ? players[i][stat].avg : espn.gamecast.translate("No stats available");
if (players[i][stat].avg != "-" && players[i][stat].RBIs > 0) {
stats += ", " + DUE.getStat(players[i][stat].RBIs) + " " + espn.gamecast.translate("RBI");
}
if (players[i][stat].avg != "-" && players[i][stat].homeRuns > 0) {
stats += ", " + DUE.getStat(players[i][stat].homeRuns) + " " + espn.gamecast.translate("HR");
}
}
$(this).attr("style", "border-top-color: " + team.color + ";").find(".bvp-player-photo").html('<img src="http://a.espncdn.com/combiner/i?img=/i/headshots/mlb/players/full/' + players[i].id + '.png&amp;w=120&amp;h=90&amp;scale=crop&amp;background=0XCCCCCC&amp;transparent=true" />').end().find(".team-logo").attr("src", "http://a2.espncdn.com/prod/assets/clubhouses/2010/mlb/logos/" + team.abbrev + ".png").end().find(".bvp-player-info").find("h2").html("<h2>" + players[i].firstName + " <br /><span>" + players[i].lastName + "</span></h2>").end().find(".heading").text(espn.gamecast.translate(stat)).end().find(".stat-line").text(stats);
});
$("#dyk p").html(dyk);
}
};
}(jQuery));
espn.gamecast.lastPlay = {};
(function($) {
var lastPlay = espn.gamecast.lastPlay;
lastPlay.update = function(play) {
if (play.eventType == 58 || (play.eventType == 57 && eval(play.isResult))) {
playText = play.playResult;
$("#lp-playText").html(playText);
}
};
lastPlay.build = function() {
var playText = espn.gamecast.translate("Currently Unavailable"),
plays = espn.gamecast.master.plays;
if (plays.length > 0) {
for (var i = 0, n = plays.length - 1; i < n; i++) {
if (plays[i].eventType == 58 || (plays[i].eventType == 57 && eval(plays[i].isResult))) {
playText = plays[i].playResult;
break;
}
}
}
$("#lp-playText").html(playText);
};
})(jQuery);
espn.gamecast.ondeck = {};
(function($) {
var ondeck = espn.gamecast.ondeck;
ondeck.update = function(hitter) {
hitter = hitter || false;
if (hitter) {
$("#od-playerId").html(ondeck.builder.html(hitter));
}
};
ondeck.builder = {
html: function(hitter) {
return '<a href="' + espn.gamecast.getPlayerLinkHREF(hitter.id) + '" class="poppable" data-playerid="' + hitter.id + '" data-position="' + hitter.position + '">' + hitter.firstName + " " + hitter.lastName + "</a>";
}
};
})(jQuery);
espn.gamecast.weather = {};
(function($) {
var WEATHER = espn.gamecast.weather,
$weather = $("#weather");
WEATHER.update = function(data) {
var temp = data.temp || "",
condition = data.condition || "",
cssClass = condition == "" ? "" : "weather-icon " + condition.toLowerCase();
$weather.find(".weather").html("<span>" + temp + "</span> " + condition).end().find("div").get(0).className = cssClass;
};
WEATHER.reset = function() {
WEATHER.update({
temp: "",
condition: ""
});
};
}(jQuery));
espn.gamecast.model = {};
(function($) {
var model = espn.gamecast.model,
batterId = 0,
pitcherId = 0,
teamBatting = "away",
teamPitching = "home",
currentBatter = null,
currentPitcher = null,
hasRun = false,
baserunners = [],
animating = false,
$scrollers = null,
currentatbatId = espn.gamecast.master.plays.length > 0 ? espn.gamecast.master.plays[0].atbatId : 0;
model.isHit = function(eventType) {
var hit = false,
hitTypes = [2, 3, 4, 6, 7, 8, 10, 11, 12, 14, 15, 16, 28, 30, 60];
for (var i = 0, l = hitTypes.length; i < l; i += 1) {
if (eventType == hitTypes[i]) {
hit = true;
break;
}
}
return hit;
};
model.getPlayerTeam = function(playerId) {
playerId = playerId || 0;
var team = "none",
loop = [espn.gamecast.master.batting.away, espn.gamecast.master.pitching.away, espn.gamecast.master.batting.home, espn.gamecast.master.pitching.home],
i, j, l;
for (i = 0; i < 4; i += 1) {
if (team == "none") {
for (j = 0, l = loop[i].length; j < l; j += 1) {
if (playerId == loop[i][j].id && loop[i][j].id != "0") {
team = i < 2 ? "away" : "home";
break;
}
}
} else {
break;
}
}
return team;
};
model.isBetweenInnings = function() {
var inningStatus = model.getInningStatus().toLowerCase();
return inningStatus == "mid" || inningStatus == "end" || model.isPregame() || inningStatus == "final" || inningStatus == "fin" || inningStatus == "mitad";
};
model.isPregame = function() {
return espn.gamecast.master.current.statusId == 1;
};
model.getPitchNumber = function(playText) {
var pnEnd = playText.indexOf(":"),
pnStart = settings.lang == "es" ? 11 : 6,
pitchNumber = pnEnd >= 0 ? parseInt(playText.substring(pnStart, pnEnd), 10) : null;
return pitchNumber;
};
model.getPlayResult = function(playText) {
var pnEnd = playText.indexOf(":"),
playResult = pnEnd >= 0 ? playText.substring(pnEnd + 2) : playText;
return playResult;
};
model.getPitchType = function(pitch) {
var playType = "play";
if (pitch.eventType == 5 || pitch.eventType == 29) {
playType = "ball";
} else {
if (pitch.eventType == 36 || pitch.eventType == 37) {
playType = "strike";
} else {
if (pitch.eventType == 13 || pitch.eventType == 21) {
playType = model.getFoulType(pitch);
}
}
}
return playType;
};
model.getFoulType = function(pitch) {
var result = pitch.playResult || "";
return result.indexOf("strike") >= 0 ? "strike" : "foul";
};
model.getCurrentPitches = function() {
var i, plays = [],
pitches = [],
playText = 0,
length = espn.gamecast.master.plays.length;
for (i = 0; i < length; i += 1) {
if (espn.gamecast.master.plays[i].summaryType == "A") {
break;
} else {
plays.push(espn.gamecast.master.plays[i]);
}
}
length = plays.length - 1;
for (i = length; i >= 0; i -= 1) {
if (plays[i].summaryType == "P") {
playText = plays[i].playText || plays[i].playResult;
pitches.push({
pitch: model.getPitchNumber(playText),
type: model.getPitchType(plays[i]),
result: model.getPlayResult(playText),
x: plays[i].pitchXCoord,
y: plays[i].pitchYCoord,
vel: plays[i].velocity
});
}
}
return pitches;
};
model.getInningStatus = function(data) {
data = data || {};
var text = data.status1 || espn.gamecast.master.current.status1,
end = settings.lang == "es" ? text.indexOf(" de la") : text.indexOf(" of");
text = end >= 0 ? text.substring(0, end) : "";
return text;
};
model.getGameStatus = function(data) {
var text, end, inningText;
if (data.inningText) {
text = data.inningText || "", end = data.inningText.indexOf(" "), inningText = end >= 0 ? text.substring(end + 1) : "";
if (data.eventType == 58 || data.eventType == 59) {
text = data.playResult != "null" ? data.playResult : "";
end = settings.lang == "es" ? text.indexOf(" de la") : text.indexOf(" of");
}
text = end >= 0 ? text.substring(0, end) : text;
} else {
text = data.status1 || "", end = settings.lang == "es" ? text.indexOf(" de la") : text.indexOf(" of");
inningText = data.status2 || "";
text = end >= 0 ? text.substring(0, end) : text;
}
return {
gameState: data.gameState,
gameDate: data.gameDate,
tvText: data.tvText,
seriesText: data.seriesText,
inning: inningText,
text: text,
balls: data.balls,
strikes: data.strikes,
outs: data.outs
};
};
model.isNewBatter = function(id) {
return id != batterId;
};
model.isNewPitcher = function(id) {
return id != pitcherId;
};
model.getBatter = function(id) {
var i, found = false,
batter = {},
away = espn.gamecast.master.batting.away,
home = espn.gamecast.master.batting.home,
al = espn.gamecast.master.batting.away.length,
hl = espn.gamecast.master.batting.home.length;
for (i = 0; i < al; i += 1) {
if (away[i].id == id) {
batter = away[i];
batter.team = espn.gamecast.master.current.away.abbrev.toLowerCase();
batter.teamColor = espn.gamecast.master.current.away.color;
found = true;
break;
}
}
if (!found) {
for (i = 0; i < hl; i += 1) {
if (home[i].id == id) {
batter = home[i];
batter.team = espn.gamecast.master.current.home.abbrev.toLowerCase();
batter.teamColor = espn.gamecast.master.current.home.color;
found = true;
break;
}
}
}
return batter;
};
model.getStance = function(batter) {
return batter.bats == "R" ? "right" : "left";
};
model.getPitcherByTeam = function(team) {
var pitchers = espn.gamecast.master.pitching[team],
pitcher = undefined;
for (var i = pitchers.length - 1; i >= 0; i -= 1) {
if (pitchers[i].id != "0") {
pitcher = pitchers[i];
break;
}
}
return pitcher;
};
model.getPitcher = function(id) {
var i, pitcher = {},
found = false,
away = espn.gamecast.master.pitching.away,
home = espn.gamecast.master.pitching.home,
al = espn.gamecast.master.pitching.away.length,
hl = espn.gamecast.master.pitching.home.length;
for (i = 0; i < al; i += 1) {
if (away[i].id == id) {
pitcher = away[i];
pitcher.team = espn.gamecast.master.current.away.abbrev.toLowerCase();
pitcher.teamColor = espn.gamecast.master.current.away.color;
found = true;
break;
}
}
if (!found) {
for (i = 0; i < hl; i += 1) {
if (home[i].id == id) {
pitcher = home[i];
pitcher.team = espn.gamecast.master.current.home.abbrev.toLowerCase();
pitcher.teamColor = espn.gamecast.master.current.home.color;
found = true;
break;
}
}
}
return pitcher;
};
model.getBaserunners = function(onBase) {
var runners = [{}, {}, {}];
for (var i = 0; i < 3; i += 1) {
if (onBase[i].id > 0) {
runners[i] = onBase[i];
}
}
return runners;
};
model.initBatterPitcher = function() {
var i, l;
for (i = 0, l = espn.gamecast.master.plays.length; i < l; i += 1) {
if (espn.gamecast.master.plays[i].batter.id > 0) {
batterId = espn.gamecast.master.plays[i].batter.id;
pitcherId = espn.gamecast.master.plays[i].pitcher.id;
break;
}
}
currentBatter = model.getBatter(batterId);
currentPitcher = model.getPitcher(pitcherId);
};
model.initTeamsBattingPitching = function() {
var status = espn.gamecast.master.current.status1,
midInn = settings.lang == "es" ? status.indexOf("Mitad") : status.indexOf("Mid");
if (midInn >= 0) {
teamBatting = "home";
} else {
if (status.indexOf("End") >= 0) {
teamBatting = "away";
} else {
if (espn.gamecast.master.plays.length > 0) {
teamBatting = parseInt(espn.gamecast.master.plays[0].halfInning, 10) % 2 == 0 ? "away" : "home";
} else {
teamBatting = "away";
}
}
}
teamPitching = teamBatting == "home" ? "away" : "home";
};
model.setModelBatterId = function(newBatterId) {
batterId = newBatterId;
};
model.getCurrentBatter = function() {
return currentBatter;
};
model.setModelPitcherId = function(newPitcherId) {
pitcherId = newPitcherId;
};
model.getCurrentPitcher = function() {
return currentPitcher;
};
model.getTeamBatting = function() {
return teamBatting;
};
model.getTeamPitching = function() {
return teamPitching;
};
model.getDefense = function(team) {
var players = espn.gamecast.master.batting[team],
pitcher = espn.gamecast.master.pitching[team][espn.gamecast.master.pitching[team].length - 2],
data = {},
positions = {
"1B": "first",
"2B": "second",
"3B": "third",
SS: "short",
C: "catcher",
LF: "left",
CF: "center",
RF: "right",
P: "pitcher"
};
for (var i = 0, l = players.length - 1; i < l; i += 1) {
if (players[i].position != "DH" && players[i].position != "PH") {
data[positions[players[i].position]] = {
position: players[i].position,
id: players[i].id,
firstName: players[i].firstName,
lastName: players[i].lastName,
href: espn.gamecast.getPlayerLinkHREF(players[i].id)
};
}
}
if (!data.pitcher) {
if (pitcher) {
data.pitcher = {
position: "P",
id: pitcher.id,
firstName: pitcher.firstName,
lastName: pitcher.lastName,
href: espn.gamecast.getPlayerLinkHREF(pitcher.id)
};
} else {
data.pitcher = {
position: "P",
id: "",
firstName: "",
lastName: "",
href: ""
};
}
}
return data;
};
model.getBattingStats = function(team) {
var mBat = espn.gamecast.master.batting[team],
len = mBat.length,
batters = [],
i;
for (i = 0; i < len; i += 1) {
if (mBat[i].id > 0) {
batters.push(mBat[i]);
}
}
batters.sort(function(a, b) {
var diff = parseInt(a.batOrder, 10) - parseInt(b.batOrder, 10);
if (diff == 0) {
if (eval(a.isStarter)) {
diff = -1;
} else {
if (eval(b.isStarter)) {
diff = 1;
}
}
}
return diff;
});
return batters;
};
model.getExpandedBattingStats = function(team) {
var batters = espn.gamecast.master.batting[team],
len = batters.length,
expanded = {
"2B": [],
"3B": [],
HR: [],
SB: []
},
i;
for (i = 0; i < len; i += 1) {
if (batters[i].id > 0) {
if (batters[i].today.doubles > 0) {
expanded["2B"].push({
name: batters[i].firstName.substr(0, 1) + ". " + batters[i].lastName,
today: batters[i].today.doubles,
season: batters[i].season.doubles
});
}
if (batters[i].today.triples > 0) {
expanded["3B"].push({
name: batters[i].firstName.substr(0, 1) + ". " + batters[i].lastName,
today: batters[i].today.triples,
season: batters[i].season.triples
});
}
if (batters[i].today.homeRuns > 0) {
expanded.HR.push({
name: batters[i].firstName.substr(0, 1) + ". " + batters[i].lastName,
today: batters[i].today.homeRuns,
season: batters[i].season.homeRuns
});
}
if (batters[i].today.stolenBases > 0) {
expanded.SB.push({
name: batters[i].firstName.substr(0, 1) + ". " + batters[i].lastName,
today: batters[i].today.stolenBases,
season: batters[i].season.stolenBases
});
}
}
}
return expanded;
};
model.getPitchingStats = function(team) {
var mPitch = espn.gamecast.master.pitching[team],
isAllStarGame = espn.gamecast.master.current.isAllStarGame,
len = mPitch.length,
pResults = espn.gamecast.master.current.pitchResult,
pitchers = [],
i;
for (i = 0; i < len; i += 1) {
if (mPitch[i].id > 0) {
if (mPitch[i].id == pResults.w.playerId) {
mPitch[i].note = "(W" + (!isAllStarGame ? ", " + pResults.w.record : "") + ")";
} else {
if (mPitch[i].id == pResults.l.playerId) {
mPitch[i].note = "(L" + (!isAllStarGame ? ", " + pResults.l.record : "") + ")";
} else {
if (mPitch[i].id == pResults.s.playerId) {
mPitch[i].note = "(S" + (!isAllStarGame ? ", " + pResults.s.record : "") + ")";
}
}
}
pitchers.push(mPitch[i]);
}
}
return pitchers;
};
model.getExpandedPitchingStats = function(team) {
var pitchers = espn.gamecast.master.pitching[team],
len = pitchers.length,
expanded = {
WP: [],
IBB: [],
HBP: [],
B: [],
BF: [],
GBFB: []
},
i;
for (i = 0; i < len; i += 1) {
if (pitchers[i].id > 0) {
if (pitchers[i].today.wildPitches > 0) {
expanded.WP.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.wildPitches
});
}
if (pitchers[i].today.intentionalWalks > 0) {
expanded.IBB.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.intentionalWalks
});
}
if (pitchers[i].today.battersHit > 0) {
expanded.HBP.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.battersHit
});
}
if (pitchers[i].today.balks > 0) {
expanded.B.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.balks
});
}
if (pitchers[i].today.battersFaced > 0) {
expanded.BF.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.battersFaced
});
}
if (pitchers[i].today.groundBallFlyBall != "0-0" && pitchers[i].today.groundBallFlyBall != "---") {
expanded.GBFB.push({
name: pitchers[i].firstName.substr(0, 1) + ". " + pitchers[i].lastName,
today: pitchers[i].today.groundBallFlyBall
});
}
}
}
return expanded;
};
model.getBoxscore = function() {
var homeTeam = espn.gamecast.getFullTeamName(espn.gamecast.master.current.home),
awayTeam = espn.gamecast.getFullTeamName(espn.gamecast.master.current.away),
homeColor = espn.gamecast.master.current.home.color,
awayColor = espn.gamecast.master.current.away.color,
home = {
hitters: model.getBattingStats("home"),
expandedBatting: model.getExpandedBattingStats("home"),
pitchers: model.getPitchingStats("home"),
expandedPitching: model.getExpandedPitchingStats("home"),
team: homeTeam,
color: homeColor
},
away = {
hitters: model.getBattingStats("away"),
expandedBatting: model.getExpandedBattingStats("away"),
pitchers: model.getPitchingStats("away"),
expandedPitching: model.getExpandedPitchingStats("away"),
team: awayTeam,
color: awayColor
};
return {
home: home,
away: away
};
};
model.getLastBatterByTeam = function(team) {
var plays = espn.gamecast.master.plays,
players = espn.gamecast.master.batting[team],
plen = plays.length,
tlen = players.length - 1,
i, j, found = false,
index = -1;
for (i = 0; i < plen; i += 1) {
for (j = 0; j < tlen; j += 1) {
if (plays[i].batter.id == players[j].id) {
found = true;
index = j;
break;
}
}
if (found) {
break;
}
}
return index;
};
model.getDueUp = function() {
var lastBatter = model.getLastBatterByTeam(teamBatting),
index = 0,
players = espn.gamecast.master.batting[teamBatting],
plen = players.length - 1,
due = [],
count = 0;
index = (lastBatter + 1 > plen) ? 0 : lastBatter + 1;
if (players.length > 1) {
while (count < 3) {
if (players[index].id != 0 && players[index].replacedBy == "0") {
due.push(players[index]);
count += 1;
}
index = (index + 1 > plen) ? 0 : index + 1;
}
} else {
due = undefined;
}
return due;
};
model.getOnDeck = function() {
var dueUp = model.getDueUp();
if (dueUp && dueUp.length >= 1) {
return dueUp[0];
} else {
return undefined;
}
};
model.getWeather = function() {
return {
temp: espn.gamecast.master.current.temp,
condition: espn.gamecast.master.current.condition
};
};
model.buildSplits = function() {
var splits = [],
currentTeamScore = parseInt(espn.gamecast.master.current.scores[teamBatting][espn.gamecast.master.current.inning - 1], 10),
currentTeamScore = isNaN(currentTeamScore) ? 0 : currentTeamScore,
plusOneRuns = parseInt(currentTeamScore, 10) + 1,
plusTwoRuns = parseInt(currentTeamScore, 10) + 2,
basesString = "",
outString = parseInt(espn.gamecast.master.current.outs, 10) == 1 ? espn.gamecast.translate("out") : espn.gamecast.translate("outs"),
numberOnBase = (espn.gamecast.master.current.onBase[0].id != 0 ? 1 : 0) + (espn.gamecast.master.current.onBase[1].id != 0 ? 1 : 0) + (espn.gamecast.master.current.onBase[2].id != 0 ? 1 : 0),
currentBatter = model.getBatter(batterId),
currentPitcher = model.getPitcher(pitcherId),
pvb = espn.gamecast.master.current.pvb,
count = espn.gamecast.master.current.countStats,
risp = espn.gamecast.master.current.rispStats;
if (numberOnBase == 0) {
basesString = espn.gamecast.translate("Bases Empty");
} else {
if (numberOnBase == 3) {
basesString = espn.gamecast.translate("Bases Loaded");
} else {
if (numberOnBase > 1) {
basesString += espn.gamecast.translate("Runners on") + " ";
} else {
basesString += espn.gamecast.translate("Runner on") + " ";
}
if (espn.gamecast.master.current.onBase[0].id != 0) {
basesString += espn.gamecast.toOrdinal(1, "f");
}
if (espn.gamecast.master.current.onBase[1].id != 0) {
basesString += espn.gamecast.master.current.onBase[0].id != 0 ? ", " : "";
basesString += espn.gamecast.toOrdinal(2, "f");
}
if (espn.gamecast.master.current.onBase[2].id != 0) {
basesString += espn.gamecast.master.current.onBase[0].id != 0 || espn.gamecast.master.current.onBase[1].id != 0 ? ", " : "";
basesString += espn.gamecast.toOrdinal(3, "f");
}
}
}
if (espn.gamecast.master.current.expectedRunsOne != 0) {
splits.push(espn.gamecast.translate("Chance of scoring") + " " + plusOneRuns + "+ " + espn.gamecast.translate("runs this inning") + " (" + espn.gamecast.master.current.outs + " " + outString + ", " + basesString + "): " + Math.round((parseFloat(espn.gamecast.master.current.expectedRunsOne) * 100) * Math.pow(10, 2)) / Math.pow(10, 2) + "%");
}
if (espn.gamecast.master.current.expectedRunsTwo != 0) {
splits.push(espn.gamecast.translate("Chance of scoring") + " " + plusTwoRuns + "+ " + espn.gamecast.translate("runs this inning") + " (" + espn.gamecast.master.current.outs + " " + outString + ", " + basesString + "): " + Math.round((parseFloat(espn.gamecast.master.current.expectedRunsTwo) * 100) * Math.pow(10, 2)) / Math.pow(10, 2) + "%");
}
if (pvb.atBats != "" && !isNaN(pvb.avg) && !isNaN(pvb.homeRuns) && !isNaN(pvb.strikeouts) && currentPitcher != undefined && currentPitcher.lastName != undefined) {
splits.push(currentBatter.lastName + " " + espn.gamecast.translate("career vs.") + " " + currentPitcher.lastName + ": " + pvb.hits + " " + espn.gamecast.translate("for") + " " + pvb.atBats + " (" + pvb.avg + " " + espn.gamecast.translate("AVG") + "), " + pvb.homeRuns + " " + espn.gamecast.translate("HR") + ", " + pvb.strikeouts + " " + espn.gamecast.translate("SO"));
}
if (count.atBats != "" && espn.gamecast.master.current.balls < 4 && espn.gamecast.master.current.strikes < 3) {
splits.push(currentBatter.lastName + " " + espn.gamecast.translate("this year") + " " + espn.gamecast.translate("after count") + " " + espn.gamecast.master.current.balls + "-" + espn.gamecast.master.current.strikes + ": " + count.hits + " " + espn.gamecast.translate("for") + " " + count.atBats + " (" + count.avg + " " + espn.gamecast.translate("AVG") + "), " + count.homeRuns + " " + espn.gamecast.translate("HR") + ", " + count.strikeouts + " " + espn.gamecast.translate("SO"));
}
if (risp.atBats != "" && (espn.gamecast.master.current.onBase[1].id != 0 || espn.gamecast.master.current.onBase[2].id != 0)) {
splits.push(currentBatter.lastName + " " + espn.gamecast.translate("this year") + " " + espn.gamecast.translate("w/ RISP") + ": " + risp.hits + " " + espn.gamecast.translate("for") + " " + risp.atBats + " (" + risp.avg + " " + espn.gamecast.translate("AVG") + "), " + risp.homeRuns + " " + espn.gamecast.translate("HR") + ", " + risp.strikeouts + " " + espn.gamecast.translate("SO"));
}
return splits;
};
model.getWLS = function() {
return {
pitchers: espn.gamecast.master.current.pitchResult
};
};
model.getStory = function() {
var preview = espn.gamecast.master.preview,
recap = espn.gamecast.master.recap,
storyData = {
storyType: "",
pitchers: espn.gamecast.master.current.pitchResult,
gameId: espn.gamecast.master.current.id,
headline: "",
byline: "",
story: ""
};
if (espn.gamecast.master.hasStory) {
if (espn.gamecast.master.current.gameState === "pregame") {
storyData.storyType = "preview";
storyData.headline = preview.headline;
storyData.byline = preview.byline;
storyData.story = preview.story;
} else {
if (recap.story != "<p></p>") {
storyData.storyType = "recap";
storyData.headline = recap.headline;
storyData.byline = recap.byline;
storyData.story = recap.story;
}
}
}
return storyData;
};
model.reset = function() {
batterId = 0;
pitcherId = 0;
teamBatting = "away";
teamPitching = "home";
currentBatter = null;
currentPitcher = null;
hasRun = false;
baserunners = [];
animating = false;
$scrollers = null;
currentatbatId = 0;
};
}(jQuery));
espn.gamecast.story = {};
(function($) {
var ST = espn.gamecast.story,
$gcStory = $("#gc-story"),
isMobile;
ST.init = function(data) {
isMobile = espn.gamecast.isMobile;
$("#gc-story").html(ST.builders.story(data));
if (isMobile && espn.gamecast.master.gameState != "live" && data.story && data.story.length > 50) {
$.getScript("http://widgets.outbrain.com/outbrain.js");
}
};
ST.builders = {
story: function(data) {
var outputHTML = "";
if (data.storyType == "recap") {
outputHTML += ST.builders.wls(data.pitchers);
}
outputHTML += '<div class="story-wrap">';
outputHTML += data.headline != "" ? '<h4 class="title"> ' + data.headline + "</h4>" : "";
outputHTML += data.byline != "" ? '<h5 class="byline">' + data.byline + "</h5>" : "";
if (isMobile) {
if (data.storyType == "recap" || data.storyType == "preview") {
outputHTML += ST.builders.video(data.storyType);
}
outputHTML += espn.gamecast.linker.convertDotcomLinksToMobileLinks(data.story, true, false);
outputHTML += ST.builders.sponsoredLinks(data.storyType);
} else {
outputHTML += data.story;
}
outputHTML += "</div>";
return outputHTML;
},
video: function(storyType) {
var getStoryVideo = function() {
var returnVideo = undefined,
vids = espn.gamecast.master[storyType].videos;
for (var i = 0, n = vids.length; i < n; i++) {
if (espn.gamecast.isVideoViewable(vids[i])) {
returnVideo = vids[i];
break;
}
}
return returnVideo;
},
gameVideo = getStoryVideo(),
outputHTML = "";
if (gameVideo && settings.lang.toLowerCase() != "es") {
outputHTML += '<div class="story-video"><img src="' + gameVideo.photo + '" /><a href="#" data-videoId="' + gameVideo.id + '" class="play-button video-highlight"><span></span></a></div>';
}
return outputHTML;
},
wls: function(pitchers) {
var outputHTML = '<div class="wls-wrap ' + (pitchers.s.playerId == 0 ? "justtwo" : "") + '">',
pitchResults = ["w", "l", "s"],
pitcher;
for (var i = 0; i < 3; i++) {
pitcher = pitchers[pitchResults[i]];
if (pitcher.playerId != 0) {
outputHTML += '<div class="' + pitchResults[i] + '-pitcher resultPitcher"><span class="resultType">' + pitchResults[i].toUpperCase() + ':</span> <a href="' + espn.gamecast.getPlayerLinkHREF(pitcher.playerId) + '" data-playerid="' + pitcher.playerId + '" class="poppable" data-position="P">' + pitcher.firstName.substring(0, 1) + ". " + pitcher.lastName + "</a>" + (espn.gamecast.master.current.isAllStarGame ? "" : '<span class="note">(' + pitcher.record + ")</span>") + "</div>";
}
}
outputHTML += '<div class="clear"></div></div>';
return outputHTML;
},
sponsoredLinks: function(storyType) {
var site = "espn",
url = "http://scores.espn.go.com/" + settings.sport + "/gamecast?gameId=" + settings.gameId;
widgetId = storyType === "preview" ? "MB_2" : "MB_3";
if (settings.lang.toLowerCase() == "es") {
url = "http://" + window.location.host + "/" + settings.sport + "/deportes/gamecast?gameId=" + settings.gameId;
site = "espndeportes";
if (3888 != 3888) {
widgetId = storyType === "preview" ? "MB_2" : "MB_4";
}
}
return '<div class="OUTBRAIN" data-src="' + url + '" data-widget-id="' + widgetId + '" data-ob-template="' + site + '"></div>';
}
};
})(jQuery);
espn.gamecast.miniBases = {};
(function($) {
var MB = espn.gamecast.miniBases,
log = espn.gamecast.debug,
$bases = $("#mobile-bases");
MB.update = function(baseRunners) {
var basesClass = MB.getBasesClass(baseRunners);
log("mini bases updated: " + basesClass);
$bases.removeClass().addClass(basesClass);
};
MB.getBasesClass = function(baseRunners) {
log(baseRunners);
var basesClass = "000";
if (baseRunners.length === 3) {
basesClass = "";
for (var i = 0; i < 3; i++) {
basesClass += baseRunners[i].id && baseRunners[i].id != 0 ? "1" : "0";
}
}
return "bases-" + basesClass.split("").join("-");
};
})(jQuery);
espn.gamecast.mainControls = {};
(function($) {
var MC = espn.gamecast.mainControls,
log = espn.gamecast.debug,
currentView = "live";
MC.toggleView = function(el) {
var $el = $(el),
view = $el.attr("data-type");
if (view != currentView) {
MC.setCurrentView(view);
MC.selectButton($el);
if (view == "live") {
MC.showField();
espn.gamecast.track("link", {
info: "menu|main|field"
});
} else {
if (view == "watch") {
MC.showWatch();
espn.gamecast.track("link", {
info: "menu|main|watch"
});
} else {
if (view == "story") {
MC.showStory();
espn.gamecast.track("link", {
info: "menu|main|story"
});
}
}
}
}
};
MC.setCurrentView = function(view) {
currentView = view;
};
MC.getCurrentView = function() {
return currentView;
};
MC.selectButton = function($el) {
$el.addClass("on").siblings().removeClass("on");
};
MC.showField = function() {
espn.gamecast.publish("viewChange", ["live"]);
};
MC.showWatch = function() {
espn.gamecast.publish("viewChange", ["watch"]);
};
MC.showStory = function() {
espn.gamecast.publish("viewChange", ["story"]);
};
})(jQuery);
var refresher = {};
(function($) {
var REF = refresher,
touches = [],
$refresh = $("#refresh-wrap"),
$content = $("#content-wrap"),
$body = $("body"),
$timestamp = $("#last-refresh-timestamp"),
pulling = false,
allowRefresh = false,
performRefresh = true,
doHack = false,
lang = settings && settings.lang ? settings.lang : "en",
REFRESHDELAY = 10000,
PULLHEIGHT = 60,
PULLTEXT = lang === "en" ? "Pull to refresh..." : "Desliza hacia abajo para refrescar...",
REFRESHTEXT = lang === "en" ? "Release to refresh..." : "Suelta para refrescar...",
LOADINGTEXT = lang === "en" ? "Loading..." : "Cargando...";
REF.refreshing = false;
REF.targetNotScrollable = function(target) {
var allow = true;
$.each($(target).parents(), function(i, ele) {
if (ele.scrollTop > 0 || ele.id == "tab-nav") {
allow = false;
return false;
}
});
return allow;
};
REF.handleTouchStart = function(e) {
if (!REF.refreshing) {
REF.resetRefresher();
allowRefresh = (window.pageYOffset === 0 && REF.targetNotScrollable(e.target));
touches.push({
pageY: e.originalEvent.changedTouches[0].pageY
});
doHack = true;
}
};
REF.handleTouchMove = function(e) {
if (!REF.refreshing) {
touches.splice(1, 1, {
pageY: e.originalEvent.changedTouches[0].pageY
});
if (touches.length === 2 && (touches[0].pageY + 5) <= touches[1].pageY) {
if (!pulling && allowRefresh) {
e.preventDefault();
pulling = true;
}
if (pulling) {
e.preventDefault();
var diff = touches[1].pageY - touches[0].pageY;
if ((diff - PULLHEIGHT) <= 0) {
$refresh.css("transform", "translate3d(0," + (diff - PULLHEIGHT) + "px,0)");
}
if (diff <= PULLHEIGHT) {
$content.css("transform", "translate3d(0," + diff + "px,0)");
}
if (diff >= PULLHEIGHT + 20) {
REF.refreshing = true;
$content.css("transform", "translate3d(0," + PULLHEIGHT + "px,0)");
$refresh.addClass("flipItGood").css("transform", "translate3d(0,0,0)").find(".refresh-msg").text(REFRESHTEXT);
}
}
doHack = false;
} else {
allowRefresh = false;
}
}
};
REF.handleTouchEnd = function(e) {
if (!REF.refreshing) {
REF.resetPull(false);
} else {
REF.refreshIt();
$refresh.addClass("refreshing");
}
if (doHack) {
REF.androidHack();
doHack = false;
}
};
REF.getReadableTime = function(d) {
var month = d.getMonth() + 1,
day = d.getDate(),
year = d.getFullYear() % 1000,
hours = d.getHours() % 12 === 0 ? 12 : d.getHours() % 12,
minutes = d.getMinutes(),
amPM = d.getHours() < 12 ? "AM" : "PM";
minutes = minutes < 10 ? "0" + minutes : minutes;
return month + "/" + day + "/" + year + ", " + hours + ":" + minutes + " " + amPM;
};
REF.refreshIt = function() {
$refresh.find(".refresh-msg").text(LOADINGTEXT);
var callback = function() {
espn.gamecast.publish("pullUpdateComplete");
};
if (performRefresh) {
try {
espn.gamecast.publish("requestUpdate", [callback]);
} catch (e) {
REF.espnMissing();
}
performRefresh = false;
setTimeout(function() {
performRefresh = true;
}, REFRESHDELAY);
} else {
setTimeout(callback, 1000);
}
};
REF.resetPull = function() {
$refresh.addClass("animate").attr("style", "").removeClass("flipItGood");
$content.addClass("animate").attr("style", "");
};
REF.resetRefresher = function() {
$refresh.removeClass("animate refreshing").find(".refresh-msg").text(PULLTEXT);
$content.removeClass("animate");
pulling = false;
allowRefresh = false;
touches = [];
};
REF.updateTime = function(dateObj) {
dateObj = dateObj ? dateObj : new Date();
$timestamp.text(REF.getReadableTime(dateObj));
};
REF.handlePullUpdate = function() {
REF.updateTime();
REF.resetPull();
REF.refreshing = false;
};
if ("ontouchstart" in window) {
$body.on("touchstart", REF.handleTouchStart);
$body.on("touchmove", REF.handleTouchMove);
$body.on("touchend", REF.handleTouchEnd);
REF.updateTime(new Date());
try {
espn.gamecast.subscribe("updateReceived", REF.updateTime);
espn.gamecast.subscribe("pullUpdateComplete", REF.handlePullUpdate);
} catch (e) {
REF.espnMissing();
}
} else {
$refresh.hide();
}
REF.espnMissing = function() {
if ("console" in window) {
console.warn("Pull to Refresh has no access to espn.gamecast object.");
}
};
var hackHeight = "auto";
REF.androidHack = function() {
if (/Android 4.0/.test(navigator.userAgent)) {
setTimeout(function() {
$content.css("height", (document.body.scrollHeight - 100) + "px");
}, 1000);
}
};
})(jQuery);
espn.gamecast.scribble = {};
(function($) {
var SCRIB = espn.gamecast.scribble,
$container = $("#commentary"),
$tab = $("#commentary-link"),
gotScribbed = false,
currentScribbleId = 0;
SCRIB.initTab = function(scribbleId, isFirstRun) {
currentScribbleId = scribbleId;
if (SCRIB.hasScribbleId(scribbleId)) {
$tab.show();
if (isFirstRun) {
$tab.children().addClass("active").parent().siblings("li").children("a").removeClass("active");
}
} else {
$tab.hide();
}
};
SCRIB.init = function() {
if (!gotScribbed) {
$.ajax({
url: "/" + settings.sport + "/gamecast/util/getScribble",
data: "scribbleId=" + currentScribbleId,
success: function(data) {
$container.html(data);
gotScribbed = true;
$container.off("click", ".posts a", SCRIB.handleLinks);
$container.on("click", ".posts a", SCRIB.handleLinks);
}
});
}
};
SCRIB.handleLinks = function(e) {
e.preventDefault();
window.open(this.href, "_blank");
};
SCRIB.reset = function() {
$container.html(" ");
gotScribbed = false;
};
SCRIB.switchEvent = function(scribbleId) {
if (scribbleId != currentScribbleId && gotScribbed) {
if (!(SCRIB.hasScribbleId(scribbleId))) {
try {
window.scribble.changeEvent("1");
} catch (e) {}
} else {
try {
window.scribble.changeEvent(scribbleId);
} catch (e) {}
}
}
};
SCRIB.hasScribbleId = function(scribbleId) {
return (scribbleId !== undefined && (scribbleId + "").length > 0);
};
})(jQuery);
var scribble = scribble || {};
scribble.callbackAnimation = function() {
jQuery(".new-item").css("background-color", "#888").animate({
backgroundColor: "#000"
}, 500, function() {
jQuery(this).attr("style", "").removeClass("new-item");
});
};
espn.gamecast.fbcomments = {};
(function($) {
var gotComments = false,
commentDiv = '<div class="fb-comments" data-href="!!url!!" data-num-posts="5" data-width="auto" data-colorscheme="dark" data-order-by="reverse_time" style="width:100%;"></div>';
espn.gamecast.fbcomments.getEm = function(commentURL, sport, lang) {
if (!gotComments) {
$.ajax({
type: "GET",
url: "/" + sport + (lang && lang.toLowerCase() === "es" ? "/deportes" : "") + "/gamecast/util/getFBComments",
data: {
lang: lang || "en"
},
success: function(data) {
$("#conversations").html('<div id="fb-root"></div>' + commentDiv.replace("!!url!!", commentURL) + data);
gotComments = true;
setTimeout(updateFBWidth, 2000);
}
});
} else {
$("#conversations").find(".fb-comments").replaceWith(commentDiv.replace("!!url!!", commentURL));
FB.XFBML.parse();
setTimeout(updateFBWidth, 1000);
}
};
var tries = 0;
function updateFBWidth() {
var $spanChild = $(".fb-comments").children("span");
if ($spanChild.length > 0 && tries < 3) {
tries++;
$spanChild.css("width", "100%").children("iframe").css("width", "100%");
} else {
if ($spanChild.length === 0 || tries < 3) {
setTimeout(updateFBWidth, 500);
}
}
}
})(jQuery);
espn.gamecast.ads = {};
window.adMgr = {};
espn.gamecast.ads.popup = espn.gamecast.ads.popup || {};
espn.gamecast.ads.popup.showing = false;
(function($) {
$(function() {
if (!espn.gamecast.isMobile && window.admgr && typeof(window.admgr.init) === "function") {
var BA = espn.gamecast.ads,
key, _banner, allSlots = [],
slots = [];
BA.refreshAd = function() {
allSlots = window.admgr.getGPTSlots();
key = $(".ad-slot-banner1").attr("id");
_banner = allSlots[key];
if (_banner) {
slots.push(_banner);
}
if (slots.length > 0) {
window.admgr.refresh(slots);
}
};
espn.gamecast.subscribe("bannerAdRefresh", BA.refreshAd);
}
});
})(jQuery);
espn.gamecast.version = {};
(function($) {
var V = espn.gamecast.version;
V.isTablet = function() {
return !this.isHandset();
};
V.isHandset = function() {
var hook = $('<div id="mobile-css-device-hook"></div>').css({
position: "absolute",
left: "-999px"
}).appendTo(document.body),
isHandset = hook.css("cursor") === "text",
memoized = function() {
return isHandset;
};
hook.remove();
this.isHandset = memoized;
return memoized.apply(this, arguments);
};
})(jQuery);
espn.gamecast.linker = {};
(function($) {
var L = espn.gamecast.linker;
L.getHomeBaseURL = function() {
return "http://m.espn.go.com/";
};
L.getSportBaseURL = function(sport) {
return L.getHomeBaseURL() + sport + "/";
};
L.getPlayercardURL = function(sport, playerId) {
return L.getSportBaseURL(sport) + "playercard?playerId=" + playerId;
};
L.getClubhouseURL = function(sport, teamAbbrev) {
return L.getSportBaseURL(sport) + "clubhouse?teamAbbrev=" + teamAbbrev;
};
L.convertDotcomLinksToMobileLinks = function(html, stripUnrecognizedLinks, makePoppable) {
var out = $('<div class="story-wrapper">' + html + "</div>");
out.find("a").each(function(i, el) {
var $el = $(el),
query = ($.parseUri(el.href || "") || {}).queryKey || {},
playerId = query.playerId || ((el.href || "").match(/\/player\/.*?_.*?\/id\/(\d+)/) || []).pop(),
teamAbbrev = query.team || ((el.href || "").match(/\/clubhouse\b.*?team=(\w+)/) || []).pop(),
mobileURL;
if (playerId) {
mobileURL = L.getPlayercardURL(settings.sport, playerId);
$el.attr("href", mobileURL);
if (makePoppable) {
$el.attr("data-playerId", playerId).addClass("poppable");
}
} else {
if (teamAbbrev) {
mobileURL = L.getClubhouseURL(settings.sport, teamAbbrev);
$el.attr("href", mobileURL);
} else {
if (stripUnrecognizedLinks) {
$el.replaceWith("<span>" + $el.text() + "</span>");
}
}
}
});
return out.html();
};
})(jQuery);
espn.gamecast.tickets = {};
(function($) {
var G = espn.gamecast,
T = G.tickets,
L = G.linker;
T.getTicketsLink = function(statusId, gameId) {
var url, keyword = espn.gamecast.appsrc === "sc" ? "scpreview" : "mobilepreview";
if (!gameId || statusId === 3) {
url = L.getSportBaseURL(settings.sport) + "teams?action=tickets&keyword=" + keyword;
} else {
url = L.getSportBaseURL(settings.sport) + "tickets?gameId=" + gameId + "&keyword=" + keyword;
}
return url;
};
G.subscribe("navChange", function(menu, $which) {
if ($which.attr("href").substring(1) === "buy-tickets" || window.location.href.indexOf("tickets") > -1) {
window.location = T.getTicketsLink(G.master.current.statusId, G.master.current.id);
}
});
})(jQuery);
espn.gamecast.alerts = {};
(function($) {
var G = espn.gamecast,
A = G.alerts;
A.getAlertsLink = function(gameId) {
return G.linker.getHomeBaseURL() + "alerts/mw/callout?type=game&sportAbbrev=" + settings.sport + "&id=" + gameId;
};
espn.gamecast.subscribe("navChange", function(menu, $which) {
if (menu !== "top" && $which.attr("href").substring(1) === "alerts") {
window.location = A.getAlertsLink(G.master.current.id);
}
});
})(jQuery);
espn.gamecast.previewMatchup = {};
(function($) {
var MU = espn.gamecast.previewMatchup,
container = $("#previewMatchup-tab");
MU.build = function(current) {
container.html(espn.gamecast.linker.convertDotcomLinksToMobileLinks(container.html(), true, false));
};
})(jQuery);
espn.gamecast.mobileAds = {};
(function($) {
$(document).ready(function() {
if (window.espn && espn.gamecast) {
espn.gamecast.subscribe("gameBreak", function(eventType) {
gamebreak();
});
}
espn.gamecast.subscribe("ready", function() {
if (espn.gamecast.isMobile) {
if (espn.gamecast.version.isHandset()) {
espn.gamecast.publish("comPlayer", [false, false, true]);
} else {
if (!skipTimer) {
espn.gamecast.publish("comPlayer", [false, false, true]);
}
}
}
});
});
window.adMgr.simulateGamebreak = function() {
gamebreak();
};
function gamebreak() {
if (window.espn.gamecast.ads.popup && window.espn.gamecast.ads.popup.showing === true) {
return;
}
if (!/hasBannerAd/.test(document.body.className)) {
document.body.className = document.body.className.trim() + " hasBannerAd";
}
if (window.admgr) {
var key, _banner, _popup, allSlots = {},
slots = [],
popup = ".ad-slot-gamebreak-popup";
allSlots = window.admgr.getGPTSlots();
key = $(".ad-slot-banner1").attr("id");
_banner = allSlots[key];
if (_banner) {
slots.push(_banner);
}
if ($(popup).length === 0) {
$("#gamebreak-popup-slot").html('<div class="ad-slot ad-slot-gamebreak-popup" data-slot-type="gamebreak-popup" data-slot-kvps="pos=gamebreak-popup"></div>');
window.admgr.registerSlot($(popup)[0], espn.ads.config);
}
key = $(popup).attr("id");
_popup = allSlots[key];
if (_popup) {
slots.push(_popup);
}
if (slots.length > 0) {
window.admgr.refresh(slots);
}
}
}
var MA = espn.gamecast.mobileAds,
skipTimer, $adPopup, $adWrap, log = espn.gamecast.debug,
firstRun = true,
adAutoClose = true;
MA.cancelCountdown = function() {
clearInterval(skipTimer);
$("#adnote-text").hide();
MA.showSkip();
};
MA.cancelAutoClose = function() {
adAutoClose = false;
};
window.adMgr.showPopupAd = function(width, height, content, options) {
$adPopup = $("#gamebreak-popup-slot");
$adWrap = $("#gamebreak-popup-wrap");
$("#adnote-text").show();
adAutoClose = true;
if (firstRun) {
firstRun = false;
}
var timeout = "",
showCountdown = false;
if (!content || content === "" || isNaN(width) || isNaN(height)) {
MA.removePreClass();
return;
}
if (options) {
if (options.timeout && !isNaN(options.timeout)) {
timeout = parseInt(options.timeout, 10);
}
if (options.onAdLoad) {
onPopupLoad = options.onAdLoad;
}
if (options.onAdClose) {
onPopupClose = options.onAdClose;
}
if (options.showCountdown) {
showCountdown = options.showCountdown;
}
}
if (!showCountdown) {
$("#adnote-text").hide();
}
skipTimer = clearInterval(skipTimer);
$adWrap.fadeIn(200, function() {
if (timeout != "") {
MA.countdown(timeout);
} else {
MA.showSkip();
}
$adPopup.html(content).show();
espn.gamecast.ads.popup = espn.gamecast.ads.popup || {};
espn.gamecast.ads.popup.showing = true;
$adWrap.css("display", "table");
$("#gamebreak-underlay").css("height", $("body").prop("scrollHeight") + "px");
});
$("#mobileadskip-link").off().on("click", MA.closePopup);
$("#mobileadskip-button").off().on("click", MA.closePopup);
};
MA.countdown = function(duration) {
skipTimer = clearInterval(skipTimer);
var start = duration,
secondString = start == 1 ? " " + espn.gamecast.translate("second") : " " + espn.gamecast.translate("seconds");
count = 1;
$("#mobilecountdown").html(start + secondString);
skipTimer = setInterval(function() {
start--;
secondString = start == 1 ? " " + espn.gamecast.translate("second") : " " + espn.gamecast.translate("seconds");
$("#mobilecountdown").html(start + secondString);
if (count >= 15 || count >= duration) {
MA.showSkip();
} else {
count++;
}
if (start <= 0) {
skipTimer = clearInterval(skipTimer);
if (adAutoClose) {
MA.closePopup();
}
}
}, 1000);
};
MA.showSkip = function() {
$("#adskip").addClass("on").removeClass("off");
};
MA.closePopup = function() {
$("#adskip").addClass("off").removeClass("on");
MA.removePreClass();
$adPopup.html("").hide();
$adWrap.hide();
espn.gamecast.ads.popup.showing = false;
skipTimer = clearInterval(skipTimer);
espn.gamecast.publish("comPlayer", [false, false, true]);
};
MA.removePreClass = function() {
$("#gamebreak-popup-wrap").removeClass("prestitial");
};
espn.gamecast.subscribe("espn.gamecast.cancelCountdown", MA.cancelCountdown);
espn.gamecast.subscribe("espn.gamecast.cancelAutoClose", MA.cancelAutoClose);
})(jQuery);
espn.gamecast.controller = {};
(function($) {
var TROLL = espn.gamecast.controller,
model = espn.gamecast.model,
master = espn.gamecast.master,
field = new espn.gamecast.field({
canvasId: "field-render"
}),
runners = espn.gamecast.baserunners,
chart = espn.gamecast.pitchZone,
list = espn.gamecast.pitchInfo,
bvp = espn.gamecast.bvp,
box = espn.gamecast.boxScore,
dueUp = espn.gamecast.dueUp,
status = espn.gamecast.gameStatus,
lastPlay = espn.gamecast.lastPlay,
activityFeed = espn.gamecast.activityFeed,
pbp = espn.gamecast.pbp,
header = espn.gamecast.header,
oots = espn.gamecast.oots,
scoringPlays = espn.gamecast.scoringPlays,
socialLinks = espn.gamecast.socialLinks,
photoGallery = espn.gamecast.photoGallery,
video = espn.gamecast.video,
ondeck = espn.gamecast.ondeck,
weather = espn.gamecast.weather,
twitter = espn.gamecast.twitterFeed,
photo = espn.gamecast.photos,
nst = espn.gamecast.nst,
battingSplits = espn.gamecast.battingSplits,
gcScribble = espn.gamecast.scribble,
mainControls = espn.gamecast.mainControls,
log = espn.gamecast.debug,
story = espn.gamecast.story,
previewMatchup = espn.gamecast.previewMatchup,
miniBases = espn.gamecast.miniBases,
gameState = espn.gamecast.master.current.gameState,
batterId = 0,
pitcherId = 0,
teamBatting = "away",
teamPitching = "home",
currentBatter = null,
currentPitcher = null,
hasRun = false,
baserunners = [],
$inningView = $("#inning-view"),
$dueUp = $("#due-up"),
$resultView = $("#main-play-text"),
$pitchView = $("#pitch-view"),
animating = false,
subFn, nSub, aSub, iSub, currentatbatId = espn.gamecast.master.plays.length > 0 ? espn.gamecast.master.plays[0].atbatId : 0,
$vidContainer = $("#video-frame"),
$watchContainer = $("#watch-frame"),
$fieldFrame = $("#field-frame"),
currentMainView = "ad",
afterAdView = "live",
isWatchInitialized = false,
isWatchStarted = false,
firstRun = true,
isMobile, currentCategory = "live",
currentTabView = "away-box",
currentPitchView = "hit-zone",
pitchViews = ["hit-zone", "hit-zone2", "pitch-list"],
pitchViewSwitchable = false,
$topMenu = $("#top-menu"),
$topMenuLinks = $topMenu.children("ul.menu").children("li").children("a"),
$subMenu = $("#sub-menu"),
$subMenuLinks = $subMenu.find("ul.submenu").children("li").children("a"),
$infoBox = $("#info-box"),
$ootWrap = $("#oot-wrap"),
$socialLinks = $("#socialLinks-wrap"),
$emptyTab = $("#empty-tab"),
$boxScoreContent = $("#box-score-content"),
$linescore = $("#linescore"),
$gcStory = $("#gc-story"),
$body = $("body"),
moduleBuilt = {
activityFeed: false,
plays: false,
"scoring-plays": false,
nst: false,
boxscore: false,
twitter: false,
"section-140": false,
cil: false,
photos: false,
videos: false,
radio: false
},
moduleContainerIds = {
activityFeed: $("#activityFeed"),
plays: $("#playbyplay"),
"scoring-plays": $("#scoringPlays"),
nst: $("#nst"),
linescore: $("#boxScore"),
"away-box": $("#boxScore"),
"home-box": $("#boxScore"),
twitter: $("#twitter-wrap"),
commentary: $("#commentary"),
"section-140": $("#conversations"),
"mobile-share": $("#mobile-share-container"),
photos: $("#photoFeed"),
videos: $("#videoFeed"),
radio: $("#radioTab")
},
getDeepHash = function() {
if (window.location.search.indexOf("gcSection") >= 0) {
return window.location.search.match(/gcSection=(.[^&#]*)/)[1];
}
return window.location.hash.substring(1);
},
deepHash = getDeepHash(),
deepLinkProps = {
boxscore: {
top: "stats",
sub: "away-box"
},
plays: {
top: "gameInfo",
sub: "plays"
},
notes: {
top: "gameInfo",
sub: "nst"
},
conversations: {
top: "social",
sub: "section-140"
},
photos: {
top: "media",
sub: "photos"
},
videos: {
top: "media",
sub: "videos"
},
social: {
top: "social",
sub: "twitter"
}
},
allowHash = !!deepLinkProps[deepHash],
mobileOnlyTabs = "|current|scores|linescore|preview-matchup|recap-story|preview-story|mobile-share|watchLive|",
pageLayout, infoBoxClasses = "gameInfo stats scores social media empty live preview recap";
TROLL.init = function() {
espn.gamecast.debug("Game Loading?...");
isMobile = espn.gamecast.isMobile;
gameState = espn.gamecast.master.current.gameState;
currentatbatId = espn.gamecast.master.plays.length > 0 ? espn.gamecast.master.plays[0].atbatId : 0;
if ($(window).width() < 926) {
pageLayout = "portrait";
$body.addClass("portrait");
} else {
pageLayout = "landscape";
$body.removeClass("portrait");
}
if (isMobile) {
video.preventAds();
}
TROLL.initializeGameView();
box.updateAll(model.getBoxscore());
status.update(model.getGameStatus(espn.gamecast.master.current));
weather.update(model.getWeather());
baserunners = model.getBaserunners(espn.gamecast.master.current.onBase);
miniBases.update(baserunners);
if (gameState == "live") {
model.initBatterPitcher();
model.initTeamsBattingPitching();
currentBatter = model.getCurrentBatter();
batterId = currentBatter ? currentBatter.id : 0;
currentPitcher = model.getCurrentPitcher();
pitcherId = currentPitcher ? currentPitcher.id : 0;
teamPitching = model.getTeamPitching();
teamBatting = model.getTeamBatting();
var currentPitches = model.getCurrentPitches();
if (batterId != 0 && pitcherId != 0) {
bvp.update({
pitcher: currentPitcher,
batter: currentBatter
});
field.sprayChart = currentBatter.sprayZone;
field.updateBatter(currentBatter.firstName + " " + currentBatter.lastName);
chart.init({
battingAverage: (currentBatter.season.avg || 0),
averages: currentBatter.hitzone,
stance: model.getStance(currentBatter),
pitches: currentPitches
});
}
field.updateDefense(model.getDefense(teamPitching));
field.setBaserunners(baserunners);
runners.init({
runners: baserunners,
field: field,
team: teamBatting,
score: espn.gamecast.master.current[teamBatting].score,
outs: espn.gamecast.master.current.outs
});
list.init(currentPitches);
var team = espn.gamecast.master.current[teamBatting];
dueUp.update({
players: model.getDueUp(),
team: {
abbrev: team.abbrev.toLowerCase(),
color: team.color,
name: team.name
},
inning: espn.gamecast.master.current.inning,
dyk: ""
});
TROLL.showInningView(true);
if (espn.gamecast.master.current.venueName != "") {
venueName = settings.lang == "es" ? espn.gamecast.master.current.venueName.replace("at", "en") : espn.gamecast.master.current.venueName, $("#stadium-info p").text(venueName + " - " + espn.gamecast.master.current.venueLoc);
}
if (typeof lastPlay !== "undefined") {
lastPlay.build();
}
if (typeof ondeck !== "undefined") {
ondeck.update(model.getOnDeck());
}
if (typeof battingSplits !== "undefined") {
battingSplits.build(model.buildSplits(), true);
}
$("#activityFeed-tab").parent().show();
} else {
$("#activityFeed-tab").removeClass("active").parent().hide().siblings(":first").children("a").addClass("active");
if (gameState === "pregame") {
$topMenu.find(".gameInfo-tab").hide();
if (!TROLL.hasLineups()) {
$topMenu.find(".stats-tab").hide();
}
$topMenuLinks.filter("[href=#social]").click();
$subMenuLinks.filter("[href=#twitter]").click();
}
}
TROLL.handleOrientationChange();
$("#home-box-link").text(espn.gamecast.master.current.home.display);
$("#away-box-link").text(espn.gamecast.master.current.away.display);
if (!firstRun) {
TROLL.handleViewChange(currentMainView);
}
if (typeof header !== "undefined") {
header.update();
}
if (typeof oots !== "undefined") {
oots.build();
if (pageLayout == "landscape") {
oots.updateTouchScrollWidth();
}
}
if (typeof socialLinks !== "undefined") {
socialLinks.build(espn.gamecast.master.current);
}
if (typeof gcScribble !== "undefined") {
gcScribble.initTab(espn.gamecast.master.scribbleId, firstRun);
}
if ($("#commentary-link").children("a").hasClass("active") && espn.gamecast.master.scribbleId == "") {
$subMenuLinks.filter("[href=#twitter]").click();
}
if (typeof photoGallery !== "undefined") {
photoGallery.init();
}
if (typeof story !== "undefined") {
story.init(model.getStory());
}
if (typeof previewMatchup !== "undefined" && isMobile && gameState == "pregame") {
previewMatchup.build(espn.gamecast.master.current);
}
TROLL.togglePitchView(currentPitchView, true);
TROLL.showTabs();
TROLL.updatePortraitNavWidth();
espn.gamecast.publish("ready");
TROLL.hideOverlay();
firstRun = false;
};
TROLL.handleSwitchGame = function(gameId) {
TROLL.hideWatchPlayer();
TROLL.showOverlay();
var masterURL = "/" + settings.sport;
if (settings.lang == "es") {
masterURL += "/deportes";
}
masterURL += "/gamecast12/master";
$.ajax({
type: "GET",
url: masterURL,
data: {
gameId: gameId,
lang: settings.lang,
init: true,
setType: true,
basic: true,
plays: true,
notes: true,
stats: true,
oots: true,
photos: true,
tweets: true,
rand: (+new Date),
scoringPlays: true,
commentary: true,
video: true
},
dataType: "json",
success: function(data) {
settings.gameId = gameId, master = data.gamecast, espn.gamecast.master = data.gamecast;
espn.gamecast.publish("ready");
batterId = 0, pitcherId = 0, baserunners = [];
try {
espn.gamecast.track("page", {
gameId: gameId
});
$("title").text("MLB GameCast - " + espn.gamecast.master.current.away.name + " vs " + espn.gamecast.master.current.home.name);
} catch (e) {}
try {
gcScribble.switchEvent(espn.gamecast.master.scribbleId);
} catch (e) {}
TROLL.reset();
TROLL.init();
}
});
};
var fakeWatchable = false,
defaultStory = true;
TROLL.initializeGameView = function() {
if (pageLayout == "landscape") {
if (!allowHash) {
var which = $topMenu.children("ul.menu").find(".active").attr("href").substring(1);
$infoBox.addClass(which);
$("#menu-" + which).find(".active").trigger("click");
}
if (defaultStory && espn.gamecast.master.hasStory && gameState != "live") {
TROLL.handleStoryView(true);
} else {
TROLL.handleStoryView(false);
if (fakeWatchable || !isMobile && espn.gamecast.master.current.isWatchable && espn.gamecast.master.current.gameState == "live") {
TROLL.initializeWatchAbility(true);
} else {
TROLL.initializeWatchAbility(false);
}
}
} else {
if (defaultStory && espn.gamecast.master.hasStory && gameState != "live") {
TROLL.handleStoryView(true);
} else {
TROLL.handleStoryView(false);
if (isMobile) {
TROLL.initializeWatchAbility(false);
TROLL.handleLiveViewSwitch();
} else {
if (fakeWatchable || espn.gamecast.master.current.isWatchable && espn.gamecast.master.current.gameState == "live") {
TROLL.initializeWatchAbility(true);
} else {
TROLL.initializeWatchAbility(false);
TROLL.handleLiveViewSwitch();
}
}
}
}
};
TROLL.initializeWatchAbility = function(watchable) {
if (watchable) {
$("#main-controls .watch-espn").css("display", "inline");
mainControls.selectButton($("#main-controls .watch-espn"));
mainControls.setCurrentView("watch");
$topMenuLinks.removeClass("active");
$("#menu-watch-default").addClass("active");
TROLL.hideSubMenu();
afterAdView = "watch";
if (!firstRun) {
currentMainView = "watch";
}
} else {
$("#main-controls .watch-espn").hide();
$("#menu-watch-default").parent().hide();
}
};
TROLL.handleStoryView = function(hasStory) {
if (hasStory) {
if (gameState == "pregame") {
$("#main-controls .recap-story").hide();
$("#main-controls .preview-story").css("display", "inline");
mainControls.selectButton($("#main-controls .preview-story"));
$("#menu-preview-story").children("a").addClass("active");
if (fakeWatchable || !isMobile && espn.gamecast.master.current.isWatchable && espn.gamecast.master.current.gameState == "live") {
TROLL.initializeWatchAbility(true);
} else {
TROLL.initializeWatchAbility(false);
}
$topMenu.find("li.recap-tab").hide();
} else {
$("#main-controls .preview-story").hide();
$("#main-controls .recap-story").css("display", "inline");
mainControls.selectButton($("#main-controls .recap-story"));
TROLL.initializeWatchAbility(false);
$topMenu.find("li.preview-tab").hide();
TROLL.hideSubMenu();
}
TROLL.hideLiveTabs();
if (firstRun) {
mainControls.setCurrentView("story");
afterAdView = "story";
} else {
currentMainView = "story";
}
TROLL.handleLiveViewSwitch();
} else {
$("#main-controls .story").hide();
$topMenu.find("li.recap-tab").hide();
$topMenu.find("li.preview-tab").hide();
if (!firstRun) {
currentMainView = "live";
}
}
};
TROLL.reset = function() {
espn.gamecast.debug("Reseting Games...");
espn.gamecast.unsubscribeAll("pitchComplete");
animating = false;
model.reset();
list.reset();
chart.reset();
bvp.reset();
field.reset();
box.reset();
status.reset();
dueUp.reset();
weather.reset();
TROLL.showPitchView();
TROLL.moduleReset();
$("#view-buttons").children("a").css("display", "inline");
$("#top-menu li").attr("style", "");
$("#top-menu a").attr("style", "");
isWatchInitialized = false;
TROLL.updateWatchGame();
};
TROLL.moduleReset = function() {
for (j in moduleBuilt) {
moduleBuilt[j] = false;
}
};
TROLL.handleLiveViewSwitch = function() {
log("pageLayout = " + pageLayout);
if (pageLayout == "portrait") {
log("currentMainView = " + currentMainView);
if (currentMainView === "ad") {
$infoBox.removeClass();
$topMenuLinks.removeClass("active");
TROLL.hideSubMenu();
log("after ad view = " + afterAdView);
if (afterAdView === "watch") {
$("#menu-watch-default").addClass("active");
currentTabView = "watchLive";
currentCategory = "watch";
mainControls.setCurrentView("watch");
} else {
if (afterAdView === "story") {
if (gameState == "final") {
$("#menu-final-default").addClass("active");
currentTabView = "recap";
currentCategory = "recap";
} else {
$("#menu-pregame-default").addClass("active");
currentTabView = "preview";
$subMenu.children().removeClass("open");
$("#menu-preview").addClass("open");
currentCategory = "preview";
TROLL.showSubMenu();
$infoBox.removeClass(infoBoxClasses).addClass(currentCategory);
}
mainControls.setCurrentView("story");
} else {
$("#menu-live-default").addClass("active");
currentTabView = "current";
currentCategory = "live";
mainControls.setCurrentView("live");
}
}
} else {
if (currentMainView == "watch") {
$("#menu-watch-default").trigger("click");
currentTabView = "watchLive";
mainControls.setCurrentView("watch");
} else {
if (currentMainView == "story") {
if (gameState == "final") {
$("#menu-final-default").trigger("click");
currentTabView = "recap";
} else {
$("#menu-pregame-default").trigger("click");
currentTabView = "preview";
TROLL.showSubMenu();
}
mainControls.setCurrentView("story");
} else {
$("#menu-live-default").trigger("click");
currentTabView = "current";
mainControls.setCurrentView("live");
}
}
}
} else {
if (currentMainView == "ad") {} else {
if (currentMainView === "watch") {
mainControls.selectButton($("#main-controls .watch-espn"));
currentTabView = "watchLive";
mainControls.setCurrentView("watch");
} else {
if (currentMainView === "story") {
if (gameState == "final") {
mainControls.selectButton($("#main-controls .recap-story"));
currentTabView = "recap";
TROLL.showStory();
} else {
mainControls.selectButton($("#main-controls .preview-story"));
currentTabView = "preview";
TROLL.showStory();
TROLL.showSubMenu();
}
mainControls.setCurrentView("story");
} else {
mainControls.selectButton($("#main-controls .game-action"));
currentTabView = "current";
mainControls.setCurrentView("live");
}
}
}
}
};
TROLL.handleGameUpdate = function(data, flag, queue) {
espn.gamecast.debug("Got a game update");
var updateGame = function() {
espn.gamecast.unsubscribe(["pitchComplete", updateGame]);
espn.gamecast.debug("Updating game");
if (model.isBetweenInnings()) {
model.initTeamsBattingPitching();
teamBatting = model.getTeamBatting();
teamPitching = model.getTeamPitching();
var team = espn.gamecast.master.current[teamBatting];
dueUp.update({
players: model.getDueUp(),
team: {
abbrev: team.abbrev.toLowerCase(),
color: team.color,
name: team.name
},
inning: espn.gamecast.master.current.inning,
dyk: ""
});
TROLL.showInningView();
}
header.update();
battingSplits.build(model.buildSplits(), false);
};
setTimeout(function() {
if (animating && TROLL.allowAnimations()) {
subFn = espn.gamecast.subscribe("pitchComplete", updateGame);
} else {
updateGame();
}
weather.update(model.getWeather());
}, 250);
if (gameState && espn.gamecast.getGameState(data.statusId) && gameState != espn.gamecast.getGameState(data.statusId)) {
window.location = window.location;
}
};
TROLL.handlePlayUpdate = function(data, flag, queue) {
if (flag) {
espn.gamecast.debug("Handle play");
espn.gamecast.debug(data);
var playText = data.playText || data.playResult,
pitchNumber = model.getPitchNumber(playText),
playResult = model.getPlayResult(playText),
playType = model.getPitchType(data),
traj = data.trajectory,
inPlay = playText.indexOf("in play") >= 0 || playText.toLowerCase().indexOf("en juego") >= 0 ? true : false,
i, l, p, handler;
if (currentatbatId == data.atbatId && (data.summaryType == "N" || data.summaryType == "S")) {
var nfn = function() {
espn.gamecast.unsubscribe(["pitchComplete", nfn]);
try {
if (currentatbatId == data.atbatId) {
if (data.isResult) {
TROLL.showPlayResult(playResult);
field.addPlayResult(playResult);
}
if (data.eventType == 57 && !hasRun) {
baserunners = model.getBaserunners(espn.gamecast.master.current.onBase);
field.setBaserunners(baserunners);
miniBases.update(baserunners);
if (currentMainView === "live") {
runners.update({
runners: baserunners,
team: teamBatting,
score: espn.gamecast.master.current[teamBatting].score,
outs: espn.gamecast.master.current.outs,
eventType: data.eventType
});
} else {
runners.init({
runners: baserunners,
team: teamBatting,
score: espn.gamecast.master.current[teamBatting].score,
outs: espn.gamecast.master.current.outs,
eventType: data.eventType
});
}
}
espn.gamecast.debug("Play result");
TROLL.showInningView();
box.updateAll(model.getBoxscore());
ondeck.update(model.getOnDeck());
status.update(model.getGameStatus(data));
lastPlay.update(data);
activityFeed.update(data, "play");
pbp.update(data);
}
} catch (e) {
espn.gamecast.debug("nfn error: " + e);
}
};
if (animating && TROLL.allowAnimations()) {
espn.gamecast.subscribe("pitchComplete", nfn);
} else {
nfn();
}
}
if (data.summaryType == "C") {
espn.gamecast.debug("Pitching change");
var cfn = function() {
espn.gamecast.unsubscribe("pitchComplete", cfn);
try {
if (model.isNewPitcher(data.pitcher.id) && teamPitching == model.getPlayerTeam(data.pitcher.id)) {
espn.gamecast.debug("new guy coming in!");
pitcherId = data.pitcher.id;
model.setModelPitcherId(pitcherId);
currentPitcher = model.getPitcher(pitcherId);
bvp.updatePitcher(currentPitcher);
box.updateAll(model.getBoxscore());
field.updatePitcher({
id: pitcherId,
firstName: currentPitcher.firstName,
lastName: currentPitcher.lastName,
href: espn.gamecast.getPlayerLinkHREF(pitcherId)
});
}
} catch (e) {
espn.gamecast.debug("cfn error: " + e);
}
};
if (animating && TROLL.allowAnimations()) {
espn.gamecast.subscribe("pitchComplete", cfn);
} else {
cfn();
}
}
if (data.summaryType == "A") {
var afn = function() {
espn.gamecast.debug("Next at bat");
espn.gamecast.unsubscribe(["pitchComplete", afn]);
TROLL.showInningView();
TROLL.showPitchView();
TROLL.updateAtBat(data);
field.removeMarks();
status.update(model.getGameStatus(data));
ondeck.update(model.getOnDeck());
lastPlay.update(data);
hasRun = false;
};
if (animating && TROLL.allowAnimations()) {
espn.gamecast.subscribe("pitchComplete", afn);
} else {
afn();
}
}
if (data.eventType == "58") {
var ifn = function() {
espn.gamecast.unsubscribe(["pitchComplete", ifn]);
field.removeMarks();
lastPlay.update(data);
status.update(model.getGameStatus(data));
activityFeed.update(data, "play");
pbp.update(data);
box.updateAll(model.getBoxscore());
hasRun = false;
try {
if (isMobile) {
setTimeout(function() {
espn.gamecast.publish("gameBreak", [data.eventType]);
}, 7000);
} else {
setTimeout(espn.gamecast.video.playAd, 7000);
}
} catch (e) {}
};
if (animating && TROLL.allowAnimations()) {
espn.gamecast.subscribe("pitchComplete", ifn);
} else {
ifn();
}
}
if (data.summaryType == "P") {
var pfn = function() {
chart.pitch({
pitch: pitchNumber,
type: playType,
x: data.pitchXCoord,
y: data.pitchYCoord
});
list.pitch({
pitch: pitchNumber,
result: playResult
});
chart.setVelType({
vel: data.velocity
});
status.update(model.getGameStatus(data));
activityFeed.update(data, "play");
pbp.update(data);
hasRun = false;
};
var efn = function() {
espn.gamecast.publish("pitchComplete", ["all set"]);
animating = false;
espn.gamecast.debug(espn.gamecast.master.current.onBase);
baserunners = model.getBaserunners(espn.gamecast.master.current.onBase);
field.setBaserunners(baserunners);
miniBases.update(baserunners);
if (TROLL.allowAnimations()) {
runners.update({
runners: baserunners,
team: teamBatting,
score: espn.gamecast.master.current[teamBatting].score,
outs: espn.gamecast.master.current.outs,
eventType: data.eventType
});
} else {
runners.init({
runners: baserunners,
team: teamBatting,
score: espn.gamecast.master.current[teamBatting].score,
outs: espn.gamecast.master.current.outs,
eventType: data.eventType
});
}
hasRun = true;
};
if (TROLL.allowAnimations()) {
traj = inPlay && traj == "null" && data.hitYCoord > 0 ? "l" : traj;
animating = true;
field.removeMarks();
field.pitch({
type: traj,
x: data.hitXCoord,
y: data.hitYCoord,
isHit: model.isHit(data.eventType),
pitchCallback: pfn,
callback: efn
});
} else {
pfn();
efn();
}
}
} else {
chart.setVelType({
vel: data.velocity
});
activityFeed.update(data, "play");
pbp.update(data);
}
};
TROLL.handleOotUpdate = function(data, flag, queue) {
espn.gamecast.debug("OOT update");
oots.update(data);
};
TROLL.handlePitcherUpdate = function(data, flag, queue) {
espn.gamecast.debug("Pitcher update");
espn.gamecast.debug(data);
if (data.replacedBy == "0") {
model.initTeamsBattingPitching();
teamPitching = model.getTeamPitching();
teamBatting = model.getTeamBatting();
espn.gamecast.debug("Player team: " + model.getPlayerTeam(data.id));
if (teamBatting != "none" && teamPitching == model.getPlayerTeam(data.id)) {
currentPitcher = model.getPitcher(data.id);
field.updateDefense(model.getDefense(teamPitching));
bvp.updatePitcher(currentPitcher);
}
}
box.updateAll(model.getBoxscore());
};
TROLL.handleBatterUpdate = function(data, flag, queue) {
espn.gamecast.debug("Batter update");
box.updateAll(model.getBoxscore());
};
TROLL.handleNstUpdate = function(data, flag, queue) {
espn.gamecast.debug("nst update");
nst.update(data, flag);
};
TROLL.handlePhotoUpdate = function(data, flag, queue) {
espn.gamecast.debug("photo update");
activityFeed.update(data, "photo");
photo.update(data, flag);
photoGallery.update(data, flag);
};
TROLL.handleTweetUpdate = function(data, flag, queue) {
espn.gamecast.debug("Tweet update");
activityFeed.update(data, "tweet");
twitter.update(data, flag);
};
TROLL.handleSPUpdate = function(data, flag, queue) {
espn.gamecast.debug("Scoring Play update");
scoringPlays.update(data, flag);
};
TROLL.handleVideoUpdate = function(data, flag, queue) {
espn.gamecast.debug("video update");
video.update(data, flag);
};
TROLL.showInningView = function(initialView) {
var lastBatter, show = function() {
model.initTeamsBattingPitching();
teamBatting = model.getTeamBatting();
teamPitching = model.getTeamPitching();
field.updateDefense(model.getDefense(teamPitching));
if (model.isBetweenInnings()) {
var dueUp = model.getDueUp(),
pitcher = model.getPitcherByTeam(teamPitching);
if (dueUp && dueUp.length >= 1) {
currentBatter = dueUp[0];
}
if (pitcher) {
currentPitcher = pitcher;
}
TROLL.showPitchView();
$inningView.addClass("hideMe").removeClass("showMe");
list.reset();
chart.reset();
bvp.reset();
ondeck.update(model.getOnDeck());
$dueUp.addClass("showMe").removeClass("hideMe");
$fieldFrame.addClass("dueUp");
} else {
field.updateDefense(model.getDefense(teamPitching));
bvp.update({
pitcher: currentPitcher,
batter: currentBatter
});
$dueUp.addClass("hideMe").removeClass("showMe");
$inningView.addClass("showMe").removeClass("hideMe");
$fieldFrame.removeClass("dueUp");
}
};
if (model.isBetweenInnings()) {
if (initialView) {
show();
} else {
setTimeout(show, 10000);
}
} else {
model.initTeamsBattingPitching();
teamPitching = model.getTeamPitching();
teamBatting = model.getTeamBatting();
field.updateDefense(model.getDefense(teamPitching));
bvp.update({
pitcher: currentPitcher,
batter: currentBatter
});
$dueUp.addClass("hideMe").removeClass("showMe");
$inningView.addClass("showMe").removeClass("hideMe");
$fieldFrame.removeClass("dueUp");
}
};
TROLL.showPlayResult = function(result) {
$resultView.find(".main-play").html(result);
$pitchView.hide();
$resultView.show();
};
TROLL.showPitchView = function() {
$resultView.hide();
$pitchView.show();
};
TROLL.updateAtBat = function(data) {
espn.gamecast.debug("Update at bat");
list.reset();
chart.reset();
model.initTeamsBattingPitching();
teamPitching = model.getTeamPitching();
teamBatting = model.getTeamBatting();
currentatbatId = data.atbatId;
if (data.pitcher.id != "0" && model.isNewPitcher(data.pitcher.id) && teamPitching == model.getPlayerTeam(data.pitcher.id)) {
espn.gamecast.debug(data.pitcher.id);
pitcherId = data.pitcher.id;
model.setModelPitcherId(pitcherId);
var pitcher = model.getPitcher(pitcherId);
espn.gamecast.debug(pitcher);
if (!espn.gamecast.isEmptyObject(pitcher)) {
currentPitcher = pitcher;
bvp.updatePitcher(currentPitcher);
field.updatePitcher({
id: pitcherId,
firstName: currentPitcher.firstName,
lastName: currentPitcher.lastName,
href: espn.gamecast.getPlayerLinkHREF(pitcherId)
});
}
}
if (data.batter.id != "0" && model.isNewBatter(data.batter.id) && teamBatting == model.getPlayerTeam(data.batter.id)) {
batterId = data.batter.id;
model.setModelBatterId(batterId);
var batter = model.getBatter(batterId);
if (!espn.gamecast.isEmptyObject(batter)) {
currentBatter = batter;
bvp.updateBatter(currentBatter);
field.sprayChart = currentBatter.sprayZone;
field.updateBatter(currentBatter.firstName + " " + currentBatter.lastName);
chart.init({
battingAverage: currentBatter.season.avg,
averages: currentBatter.hitzone,
stance: model.getStance(currentBatter)
});
}
}
box.updateAll(model.getBoxscore());
espn.gamecast.publish("atBatUpdated");
};
TROLL.handleNavChange = function(menu, $which, e) {
var newView = $which.attr("href").substring(1),
$subNavSiblings, $currentActiveSub, category, tabToBuild = "";
if (currentMainView !== "ad" || pageLayout === "landscape") {
if (menu === "top") {
$topMenuLinks.removeClass("active");
$which.addClass("active");
$("#menu-" + newView).addClass("open").siblings().removeClass("open");
$infoBox.removeClass(infoBoxClasses).addClass(newView);
$currentActiveSub = $("#menu-" + newView).find("a.active");
if ($currentActiveSub && $currentActiveSub.length == 0) {
$currentActiveSub = $("#menu-" + newView).find("a:first").addClass("active");
}
tabToBuild = $currentActiveSub.attr("href").substring(1);
category = newView;
if (!e.isTrigger) {
espn.gamecast.track("link", {
info: "menu|top|" + category
});
}
} else {
if (menu === "sub") {
$which.addClass("active").parent().siblings("li").children("a").removeClass("active");
tabToBuild = newView;
category = $which.parents("ul.submenu").parent().attr("id").substring(5);
if (!e.isTrigger) {
espn.gamecast.track("link", {
info: "menu|sub|" + tabToBuild
});
}
}
}
if (!moduleBuilt[tabToBuild]) {
TROLL.buildModule(tabToBuild);
moduleBuilt[tabToBuild] = true;
}
currentCategory = category;
currentTabView = tabToBuild;
log("---------START-----------");
log("tabToBuild = " + tabToBuild);
log("category = " + category);
log("currentMainView = " + currentMainView);
log("---------END-------------");
if (category !== "live" && pageLayout == "portrait") {
$fieldFrame.addClass("hideElements");
} else {
if (currentMainView == "live") {
$fieldFrame.removeClass("hideElements");
}
}
if (category !== "scores") {
$ootWrap.removeClass("show");
} else {
$ootWrap.addClass("show");
TROLL.hideSubMenu();
}
if (category !== "watch" && pageLayout == "portrait") {}
if (currentMainView == "story" && pageLayout == "portrait" && (category != "recap" || category != "preview")) {
TROLL.hideStory();
}
if (category === "stats") {
TROLL.showSubMenu();
$boxScoreContent.removeClass().addClass(tabToBuild);
if (tabToBuild == "linescore") {
$linescore.show();
}
} else {
if (category == "live") {
TROLL.hideSubMenu();
TROLL.handleViewChange("live");
} else {
if (category == "watch") {
TROLL.hideSubMenu();
TROLL.handleViewChange("watch");
} else {
if (category == "preview") {
TROLL.showSubMenu();
if (tabToBuild == "preview-matchup") {
TROLL.hideStory();
} else {
if (tabToBuild == "preview-story") {
TROLL.handleViewChange("story");
}
}
} else {
if (category == "recap") {
TROLL.hideSubMenu();
TROLL.handleViewChange("story");
} else {
if (category !== "scores") {
TROLL.showSubMenu();
if (tabToBuild == "mobile-share") {
$emptyTab.show().siblings("." + category).removeClass("active");
$socialLinks.show();
} else {
moduleContainerIds[tabToBuild].addClass("active").siblings("." + category).removeClass("active");
}
}
}
}
}
}
}
if (tabToBuild !== "mobile-share") {
$socialLinks.css("display", "");
}
if (tabToBuild !== "linescore") {
$linescore.css("display", "");
}
}
};
TROLL.navControls = function($which) {
if ($which.hasClass("right")) {
TROLL.handleMenuNext($which);
} else {
if ($which.hasClass("left")) {
TROLL.handleMenuPrev($which);
}
}
};
TROLL.handleMenuNext = function($which) {
var $button = $which,
$nav = $topMenu.children("ul.menu"),
navWidth = $topMenu.outerWidth() - ($topMenu.children(".button.left").outerWidth() + $topMenu.children(".button.right").outerWidth()),
currentPosition = $nav.offset().left * -1,
links = $nav.children("li:visible"),
listWidth = 0,
extraMargin = 10,
newPosition, numLinksLeft = 1;
links.each(function() {
listWidth += $(this).outerWidth();
});
for (var i = 0, n = links.length; i < n; i++) {
if (($(links[i]).position().left + $(links[i]).outerWidth()) > (currentPosition + navWidth)) {
numLinksLeft = n - i;
newPosition = $(links[i]).position().left * -1;
$nav.stop(true, true).animate({
left: newPosition + "px"
}, 500, function() {
$(this).css("left", newPosition + "px");
});
break;
}
}
if (newPosition && (((newPosition - (numLinksLeft * links.last().outerWidth()) - extraMargin) * -1) >= listWidth)) {
$button.addClass("disabled");
$button.siblings(".button").removeClass("disabled");
} else {
if (newPosition && newPosition < 0) {
$button.siblings(".button").removeClass("disabled");
}
}
};
TROLL.handleMenuPrev = function($which) {
var $button = $which,
$nav = $topMenu.children("ul.menu"),
navWidth = $topMenu.outerWidth() - ($topMenu.children(".button.left").outerWidth() + $topMenu.children(".button.right").outerWidth()),
currentPosition = -1 * $nav.position().left,
links = $nav.children("li:visible"),
newPosition = currentPosition;
for (var i = 0, n = links.length; i < n; i++) {
if ($(links[i]).position().left > (currentPosition - navWidth)) {
newPosition = $(links[i]).position().left * -1;
$nav.stop(true, true).animate({
left: newPosition + "px"
}, 500, function() {
$(this).css("left", newPosition + "px");
});
break;
}
}
if (newPosition == 0) {
$button.addClass("disabled");
$button.siblings(".button").removeClass("disabled");
}
};
TROLL.buildModule = function(which) {
if (which == "activityFeed" && typeof activityFeed !== "undefined") {
activityFeed.build();
} else {
if (which == "plays" && typeof pbp !== "undefined") {
pbp.build();
} else {
if (which == "scoring-plays" && typeof scoringPlays !== "undefined") {
scoringPlays.build();
} else {
if (which == "nst" && typeof nst !== "undefined") {
nst.build(espn.gamecast.master.nst);
} else {
if (which == "twitter" && typeof twitter !== "undefined") {
twitter.build(espn.gamecast.master.tweets);
} else {
if (which === "commentary" && typeof gcScribble !== "undefined") {
gcScribble.init();
} else {
if (which == "photos" && typeof photo !== "undefined") {
photo.build(espn.gamecast.master.photos);
} else {
if (which == "videos" && typeof video !== "undefined") {
video.build(espn.gamecast.master.videos);
} else {
if (which == "radio" && typeof espn.gamecast.audio !== "undefined") {
espn.gamecast.audio.build();
} else {
if (which == "section-140") {
var fbcommentURL = espn.gamecast.getCommentURL();
espn.gamecast.fbcomments.getEm(fbcommentURL, settings.sport, settings.lang);
}
}
}
}
}
}
}
}
}
}
};
TROLL.togglePitchView = function(view, firstRun) {
if (pitchViewSwitchable) {
var curIndex = pitchViews.indexOf(currentPitchView);
if (view === undefined) {
view = curIndex + 1 === pitchViews.length ? pitchViews[0] : pitchViews[curIndex + 1];
}
currentPitchView = view;
$pitchView.removeClass().addClass(view);
if (!firstRun && currentPitchView.indexOf("hit-zone") >= 0) {
chart.toggleHeatMap();
}
} else {
if (firstRun) {
$pitchView.addClass(view);
}
}
};
TROLL.handleReplay = function(data) {
if (currentMainView === "live") {
var callback = function() {
field.addPlayResult(data.result);
espn.gamecast.publish("replayComplete", []);
};
field.removeMarks();
field.pitch({
isHit: espn.gamecast.model.isHit(data.eventType),
type: data.type,
x: data.x,
y: data.y,
callback: function() {
setTimeout(callback, 500);
log("Callback.");
}
});
}
};
TROLL.showTabs = function() {
$topMenu.removeClass("vidHide");
};
TROLL.updatePortraitNavWidth = function() {
if ($body.hasClass("iPadScroll") && pageLayout === "portrait") {
var totalMenuWidth = 0;
$("#top-menu").find("li").each(function() {
if ($(this).is(":visible")) {
totalMenuWidth += $(this).outerWidth();
}
});
$("#top-menu").children("ul").css("width", totalMenuWidth + "px");
}
};
var mainViews = "|live|story|watch|preview|recap|";
TROLL.handleComPlayer = function(isPlaying, isHighlight, isAdSkip) {
log("Playing? " + isPlaying + " .. Highlight? " + isHighlight + " .. isAdSkip? " + isAdSkip);
if (isPlaying === true) {
if (currentMainView == "watch" && isHighlight) {
espn.watchespn.pause();
TROLL.handleViewChange("ad");
} else {
if (currentMainView != "watch") {
TROLL.handleViewChange("ad");
} else {
if (currentMainView == "watch" && !isHighlight) {
video.skipAd();
}
}
}
} else {
if (isPlaying === false) {
log("currentMainView == " + currentMainView);
if ((!firstRun && (isAdSkip || isHighlight)) || (isMobile && firstRun && isAdSkip)) {
currentMainView = afterAdView;
}
if (currentMainView == "watch") {
espn.watchespn.resume();
}
if (pageLayout == "landscape" || mainViews.indexOf(currentCategory) >= 0) {
TROLL.handleViewChange(currentMainView);
allowHash && TROLL.handleDeepLink();
} else {
TROLL.hideAdPlayer();
}
}
}
};
TROLL.updateWatchGame = function() {
if (espn.gamecast.master.current.isWatchable && espn.watchespn != undefined) {
espn.watchespn.changeGame(espn.gamecast.master.current.id, settings.sport);
}
};
TROLL.initializeWatchESPN = function() {
isWatchInitialized = true;
};
viewActions = {
live: function() {
video.setAdTimer();
video.allowAds();
TROLL.showFieldFrame();
},
watch: function() {
video.clearAdTimer();
video.preventAds();
TROLL.showWatchPlayer();
},
ad: function() {
TROLL.showAdPlayer();
},
story: function() {
TROLL.showStory();
}
};
TROLL.showFieldFrame = function() {
log("showing field...");
TROLL.hideAdPlayer();
TROLL.hideWatchPlayer();
TROLL.hideStory();
if (pageLayout != "portrait" || (pageLayout == "portrait" && currentTabView == "current")) {
$fieldFrame.removeClass("hideElements");
}
};
TROLL.showAdPlayer = function() {
log("Showing ad player");
TROLL.hideFieldFrame();
TROLL.hideWatchPlayer();
TROLL.hideStory();
$vidContainer.removeClass("vidHide");
oots.shade(true);
};
TROLL.showWatchPlayer = function() {
log("showing watch...");
if (isWatchInitialized) {
if (isWatchStarted) {
espn.watchespn.play();
} else {
try {
espn.watchespn.start();
} catch (e) {}
isWatchStarted = true;
}
} else {
log("watch is not initialized");
}
TROLL.hideAdPlayer();
TROLL.hideFieldFrame();
TROLL.hideStory();
$watchContainer.removeClass("vidHide");
};
TROLL.showStory = function() {
log("showing story...");
TROLL.hideFieldFrame();
TROLL.hideAdPlayer();
TROLL.hideWatchPlayer();
$gcStory.removeClass("vidHide");
};
TROLL.hideAdPlayer = function() {
log("hiding ad player");
$vidContainer.addClass("vidHide");
oots.shade(false);
};
TROLL.hideWatchPlayer = function() {
log("hiding watch player");
if (espn.watchespn) {
espn.watchespn.stop();
}
$watchContainer.addClass("vidHide");
};
TROLL.hideFieldFrame = function() {
log("hiding field frame");
$fieldFrame.addClass("hideElements");
};
TROLL.hideStory = function() {
log("hiding story..");
$gcStory.addClass("vidHide");
};
TROLL.handleViewChange = function(view) {
if (view != "ad") {
afterAdView = view;
}
currentMainView = view;
TROLL.toggleView(view);
};
TROLL.toggleView = function(view) {
viewActions[view] && viewActions[view](view);
};
var prevWidth = $(window).width();
TROLL.handleOrientationChange = function() {
var currentWidth = $(window).width(),
largeField = currentWidth >= 480 ? true : false,
newWidth, newHeight;
if (prevWidth >= 926 && currentWidth < 926) {
pageLayout = "portrait";
$body.addClass("portrait");
TROLL.handleLiveViewSwitch();
prevWidth = currentWidth;
$("#oot-games").css("width", "");
TROLL.updatePortraitNavWidth();
} else {
if (prevWidth < 926 && currentWidth >= 926) {
log("currentTabView = " + currentTabView + " and this: mobileOnlyTabs.indexOf(currentTabView) = " + mobileOnlyTabs.indexOf(currentTabView));
if (mobileOnlyTabs.indexOf(currentTabView) != -1) {
if (gameState == "pregame") {
$topMenuLinks.filter("[href=#social]").click();
$subMenuLinks.filter("[href=#twitter]").click();
} else {
$topMenuLinks.filter("[href=#stats]").click();
$subMenuLinks.filter("[href=#away-box]").click();
}
}
$body.removeClass("portrait");
pageLayout = "landscape";
if (currentMainView === "live") {
$fieldFrame.removeClass("hideElements");
}
TROLL.handleLiveViewSwitch();
prevWidth = currentWidth;
if (typeof oots !== "undefined") {
oots.updateTouchScrollWidth();
}
}
}
if (currentWidth <= 660) {
pitchViewSwitchable = true;
} else {
pitchViewSwitchable = false;
}
if (largeField) {
field.max = 470;
field.homeX = 235;
field.homeY = 147;
field.rubberX = 235;
field.rubberY = 110;
field.firstX = 310;
field.firstY = 110;
field.secondX = 235;
field.secondY = 84;
field.thirdX = 160;
field.thirdY = 110;
field.home = [field.homeX, field.homeY, 5];
field.first = [field.firstX, field.firstY, 4];
field.second = [field.secondX, field.secondY, 3];
field.third = [field.thirdX, field.thirdY, 4];
field.plate = [field.homeX, field.homeY, 3];
newWidth = 475;
newHeight = 173;
} else {
field.max = 315;
field.homeX = 158;
field.homeY = 100;
field.rubberX = 158;
field.rubberY = 75;
field.firstX = 208;
field.firstY = 75;
field.secondX = 158;
field.secondY = 57;
field.thirdX = 108;
field.thirdY = 75;
field.home = [field.homeX, field.homeY, 5];
field.first = [field.firstX, field.firstY, 4];
field.second = [field.secondX, field.secondY, 3];
field.third = [field.thirdX, field.thirdY, 4];
field.plate = [field.homeX, field.homeY, 3];
newWidth = 320;
newHeight = 117;
}
field.handleResize({
canvasId: "field-render",
width: newWidth,
height: newHeight
});
field.adjustDefense();
TROLL.resetTouchScroll();
};
TROLL.resetTouchScroll = function() {
var $ss = $(".superscroller");
$ss.removeClass("whatmakesmesuper");
setTimeout(function() {
$ss.addClass("whatmakesmesuper");
}, 200);
};
TROLL.showOverlay = function() {
$("#overlay").show();
};
TROLL.hideOverlay = function() {
$("#overlay").fadeOut();
};
TROLL.hideSubMenu = function() {
$subMenu.addClass("hide");
};
TROLL.showSubMenu = function() {
$subMenu.removeClass("hide");
};
TROLL.hideLiveTabs = function() {
$("#main-controls .game-action").css("display", "none");
$("#menu-live-default").hide();
};
TROLL.showLiveTabs = function() {
$("#main-controls .game-action").css("display", "inline");
$("#menu-live-default").show();
};
TROLL.allowAnimations = function() {
var allow = false;
if (pageLayout == "landscape" && currentMainView == "live") {
allow = true;
} else {
if (pageLayout == "portrait" && currentCategory == "live") {
allow = true;
}
}
return allow;
};
TROLL.handleDeepLink = function() {
var deepLink = deepLinkProps[deepHash];
currentCategory = deepLink.top;
currentTabView = deepLink.sub;
$topMenuLinks.filter("[href=#" + deepLink.top + "]").click();
$subMenuLinks.filter("[href=#" + deepLink.sub + "]").click();
allowHash = false;
};
TROLL.hasLineups = function() {
var box = model.getBoxscore();
return box.home.hitters.length >= 9 && box.away.hitters.length >= 9 && box.home.pitchers.length >= 1 && box.away.pitchers.length >= 1;
};
espn.gamecast.subscribe("switchGame", TROLL.handleSwitchGame);
espn.gamecast.subscribe("gameUpdate", TROLL.handleGameUpdate);
espn.gamecast.subscribe("ootUpdate", TROLL.handleOotUpdate);
espn.gamecast.subscribe("playUpdate", TROLL.handlePlayUpdate);
espn.gamecast.subscribe("pitcherUpdate", TROLL.handlePitcherUpdate);
espn.gamecast.subscribe("batterUpdate", TROLL.handleBatterUpdate);
espn.gamecast.subscribe("nstUpdate", TROLL.handleNstUpdate);
espn.gamecast.subscribe("photoUpdate", TROLL.handlePhotoUpdate);
espn.gamecast.subscribe("tweetUpdate", TROLL.handleTweetUpdate);
espn.gamecast.subscribe("spUpdate", TROLL.handleSPUpdate);
espn.gamecast.subscribe("comUpdate", TROLL.handleCommentaryUpdate);
espn.gamecast.subscribe("videoUpdate", TROLL.handleVideoUpdate);
espn.gamecast.subscribe("replay", TROLL.handleReplay);
espn.gamecast.subscribe("viewChange", TROLL.handleViewChange);
espn.gamecast.subscribe("comPlayer", TROLL.handleComPlayer);
$.subscribe("espn.watchespn.init", TROLL.initializeWatchESPN);
espn.gamecast.subscribe("hideWatch", TROLL.hideWatchPlayer);
espn.gamecast.subscribe("showWatch", function() {
if (currentMainView == "watch") {
TROLL.showWatchPlayer();
}
});
espn.gamecast.subscribe("navChange", TROLL.handleNavChange);
espn.gamecast.subscribe("navControl", TROLL.navControls);
espn.gamecast.subscribe("orientationChange", TROLL.handleOrientationChange);
espn.gamecast.subscribe("pitchViewChange", TROLL.togglePitchView);
$(document).ready(function() {
var toggleBaserunners = function(e) {
field.toggleBaserunners.call(field, e);
},
toggleDefense = function(e) {
field.toggleDefense.call(field, e);
},
toggleSprayChart = function(e) {
field.toggleSprayChart.call(field, e);
};
$("#toggle-baserunners").click(toggleBaserunners);
$("#toggle-defense").click(toggleDefense);
$("#toggle-spray-chart").click(toggleSprayChart);
$topMenuLinks.on("click", function(e) {
e.preventDefault();
espn.gamecast.publish("navChange", ["top", $(this), e]);
});
$subMenuLinks.on("click", function(e) {
e.preventDefault();
espn.gamecast.publish("navChange", ["sub", $(this), e]);
});
if ($body.hasClass("iPadScroll")) {
$("#menu-next, #menu-prev").hide();
} else {
$("#menu-next, #menu-prev").on("click", function(e) {
e.preventDefault();
espn.gamecast.publish("navControl", [$(this)]);
});
}
TROLL.init();
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment