/*
comEspnGamesCore included
crossDomainRequest included
popPlayerCard included
formatNumberTea included
flexpop included
The above blocks of code can be excluded and included through the query string.  For example:
/lm/static/js/popPlayerCard?exclude=comEspnGamesCore,crossDomainRequest
*/

/* start comEspnGamesCore */


/*Begin ESPN.com core*/
com = {
	espn:{
		env:{},
		listeners:{},

		games:{}
	}
};
com.espn.env.av = navigator.appVersion;
com.espn.env.ua = navigator.userAgent;
com.espn.env.an = navigator.appName;
com.espn.env.platform = navigator.platform;

com.espn.env.IE = "Microsoft Internet Explorer";
com.espn.env.NS = "Netscape";
com.espn.env.MAC = "MacPPC";
/* end comEspnGamesCore */

/* start crossDomainRequest */


/* You should be using:
CrossDomain.request(url, options)
CrossDomain.insertScript(url)
*/

var CrossDomain = {};
CrossDomain.SWFID = 'crossDomainRequestSWF';
CrossDomain.callbackOptions = [];

CrossDomain.createXHR = function() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}
	
	try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
	try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
	try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
	try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
	return false; /* no XHR support */
}

CrossDomain.sameDomainRequest = function(url, options) {
	var xhr = CrossDomain.createXHR()
	if(!xhr) { return false; }
	
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			var responseJSON = (options.parseJSON) ? CrossDomain.parseJSON(xhr.responseText) : null;
			var response = {responseText:xhr.responseText, responseXML:xhr.responseXML, statusCode:xhr.status, responseJSON:responseJSON}
			if (xhr.status >= 200 && xhr.status < 300 && options.onSuccess) {
				options.onSuccess(response);
			} else if (xhr.status >= 400 && options.onError) {
				options.onError(response);
			} else if (options.onComplete) {
				options.onComplete(response);
			}
		}
	}
	
	var paramString = ''
	if (options.parameters) {
		var delim = '';
		for(option in options.parameters) {
			paramString+=delim+option+'='+options.parameters[option];
			delim = '&';
		}
	}
	
	var body = (options.method == 'POST') ? paramString : '';
	var urlAndQueryString = (options.method == 'POST' || paramString == '') ? url : url+'?'+paramString;
	
	try {
		xhr.open(options.method, urlAndQueryString, true);
		xhr.send(body);
	} catch(e) {
		return false;
	}

	return true;
}

CrossDomain.setDefaultOptions = function(options) {
	if (!options) {
		options = {};
	}
	options.method = (options.method == 'POST' || options.method == 'post') ? 'POST' : 'GET';
	options.parseXML = (options.parseXML == true);
	options.parseJSON = (options.parseJSON == true);
	options.timeout = (options.timeout && options.timeout > 0 && options.timeout < 100000) ? options.timeout : 15000;
	options.useCodepage = (options.useCodepage == true);
	options.timestamp = new Date().getTime();

	/* convert query string to parameters map */
	if (options.parameters && options.parameters.length && options.parameters.split) {
		parameters = {};
		var paramArray = options.parameters.split('&');
		for (var i=0; i<paramArray.length; ++i) {
			var pair = paramArray[i].split('=');
			if (pair.length == 2) {
				parameters[pair[0]] = pair[1];
			}
		}
		options.parameters = parameters;
	}
	return options;
}

CrossDomain.parseXML = function(text) {
	var parsed = null;
	try {
		if (document.implementation.createDocument) {
			parsed = (new DOMParser()).parseFromString(text,'text/xml');
		} else if (window.ActiveXObject) {
			parsed = new ActiveXObject('Microsoft.XMLDOM');
			parsed.async='false';
			parsed.loadXML(text);
		}
	} catch (e) {}
	return parsed;
}

CrossDomain.parseJSON = function(text) {
	var parsed = null;
	try {
		parsed = eval('(' + responseText + ')');
	} catch (e) {}
	return parsed;
}

CrossDomain.insertSWF = function() {
	if (!swfobject || !swfobject.hasFlashPlayerVersion) {
		return false; /* page needs to include SWFObject */
	}

	if (!document.getElementById(CrossDomain.SWFID)) { /* only render SWF once */
		if (!swfobject.hasFlashPlayerVersion("8")) {
			return false; /* required Flash version not installed */
		}
		
		var placeHolder = document.createElement("div");
		placeHolder.id = CrossDomain.SWFID;
		document.body.appendChild(placeHolder);
		
		var flashvars = {
		};
		var params = {
			allowScriptAccess: "always",
			allowNetworking: "all"
		};
		var attributes = {
			style: "position:absolute;top:-100px;"
		};
		swfobject.embedSWF("http://g.espncdn.com/s/crossdomainrequest/crossdomain2.swf", CrossDomain.SWFID, "1", "1", "8", false, flashvars, params, attributes);
		
	}
	return true;
}

CrossDomain.storeCallback = function(options) {
	var index = CrossDomain.callbackOptions.push(options)-1;
	
	CrossDomain.callbackOptions[index].callback = function(responseText, statusCode) {
		var storedOptions = CrossDomain.callbackOptions[index];
		if (storedOptions != null) {
			CrossDomain.callbackOptions[index] = null;

			if (statusCode < 100) {
				statusCode = null; /* older browsers don't convey http status code to swf */
			}

			var responseXML = (storedOptions.parseXML) ? CrossDomain.parseXML(responseText) : null;
			var responseJSON = (storedOptions.parseJSON) ? CrossDomain.parseJSON(responseText) : null;

			if (storedOptions.onComplete) {
				storedOptions.onComplete({responseText:responseText, responseXML:responseXML, statusCode:statusCode, responseJSON:responseJSON});
			}
		}
	}
	
	window.setTimeout(function(){
		if (CrossDomain.callbackOptions[index] != null) {
			CrossDomain.callbackOptions[index].callback();
		}
	}, options.timeout); /* in case the response never comes back from swf */
	
	return index;
}

CrossDomain.makeRequestThroughSWF = function(options, callbackIndex) {
	if(!document.getElementById(CrossDomain.SWFID)) {
		return false; /* SWF not inserted */
	} else if (!document.getElementById(CrossDomain.SWFID).makeCrossDomainRequest) {
		if (!CrossDomain.queuedRequests) {
			CrossDomain.queuedRequests = [];
			CrossDomain.intervalId = window.setInterval(function(){
				if (document.getElementById(CrossDomain.SWFID).makeCrossDomainRequest) {
					window.clearInterval(CrossDomain.intervalId);
					CrossDomain.intervalId = null;
					while(CrossDomain.queuedRequests.length > 0) {
						var callbackIndex = CrossDomain.queuedRequests.shift();
						options = CrossDomain.callbackOptions[callbackIndex];
						CrossDomain.makeRequestThroughSWF(options, callbackIndex);
					}
					CrossDomain.queuedRequests = null;
				}
			}, 100);
		}
		CrossDomain.queuedRequests.push(callbackIndex);
	} else {
		document.getElementById(CrossDomain.SWFID).makeCrossDomainRequest(options.url, options.parameters, options.method, 'CrossDomain.callbackOptions['+callbackIndex+'].callback');
	}
	return true;
}

CrossDomain.request = function(url, options) {
	if (!document.getElementById) {
		return false; /* get a better browser! */
	}
	
	options = CrossDomain.setDefaultOptions(options);
	options.url = url;
	
	var successfullRequest = !options.useSWF && CrossDomain.sameDomainRequest(url, options);
	if (successfullRequest) {
		return true;
	}

	if (!CrossDomain.insertSWF()) {
		return false;
	}
	var callbackIndex = CrossDomain.storeCallback(options);
	return CrossDomain.makeRequestThroughSWF(options, callbackIndex);
};

CrossDomain.insertScript = function(url) {
	if (!url || !document.createElement) { return false; }

	var script = document.createElement('script');
	script.setAttribute('src', url);
	script.setAttribute('type', 'text/javascript');
	(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
	
	return true;
};


/* Old Syntax.  Instead, call CrossDomain.request() and CrossDomain.insertSWF() directly. */
function crossDomainRequest(url, options) {
	return (url) ? CrossDomain.request(url, options) : CrossDomain.insertSWF();
}
/* end crossDomainRequest */

/* start popPlayerCard */

// POP PLAYER CARD
var Ppc = {};
// ESC KEY CLOSE
Ppc.escClose = function() {
	jQuery(document).keypress(function(e) {
		 var key = e.keyCode || e.wich;
		 if (key && (key == 27)) { Flexpop.remove("_ppc"); }
	});
}
// TOGGLE GAME LOG STATS
Ppc.toggleStatsView = function(name, vCurrent, vNext) {
	var current = '#moreStatsView' + vCurrent;
	var next = '#moreStatsView' + vNext;
	jQuery(current).css({ display: 'none'});
	jQuery(next).css({ display: 'block'});
}
// CHARTS STAT NAV
Ppc.chartsStatNav = function(backForward, incomingTop) {

	var lineHeight = 28; /* DEFAULT LINE HEIGHT */ 
	var divHeight = jQuery("#chart-nav-stats").height(); 
	var currentTop = jQuery("#chart-nav-stats").position().top;
	
	/* PAGINATE TO SELECTED STAT ROW */
	if (incomingTop != null) { currentTop = incomingTop; }

	if (backForward == "backward" && currentTop + lineHeight <= 0) { 
		var newTop = currentTop + lineHeight; 
	} else if (backForward == "forward" && (currentTop - lineHeight)*-1 < divHeight) { 
		var newTop = currentTop - lineHeight; }
	else { 
		var newTop = currentTop; 
	}

	jQuery("#chart-nav-stats").css({ top: newTop+'px' });
	
	/* HIDE SHOW NAV ARROWS */
	var lArrowDisplay = "visible";
	var rArrowDisplay = "visible";

	if (newTop == 0) { lArrowDisplay = "hidden"; }
	if ((newTop * -1) + lineHeight >= divHeight) { rArrowDisplay = "hidden"; }

	jQuery("#chart-nav-left-arrow").css({ visibility: lArrowDisplay });
	jQuery("#chart-nav-right-arrow").css({ visibility: rArrowDisplay });
	
}
// RENDER CHART
Ppc.renderContentCharts = function(options) {
	var url = 'http://'+o.host+'/'+o.gameRoot+'/format/playerpop/charts';
			
	// BUILD CHART PARAM
	var pars = 'playerId=' + options.playerId + '&playerIdType=' + options.playerIdType;
	if (options.leagueId > 0) { pars += '&leagueId=' + options.leagueId + '&teamId=' + options.teamId; }
	if (options.seasonId > 0) { pars += '&seasonId=' + options.seasonId; }
	if (options && options.statId != null) { pars += '&statId=' + options.statId }
	if (options && options.addlPlayerIds) { pars += '&addlPlayerIds=' + options.addlPlayerIds }
	if (options && options.chartSplitType) { pars += '&chartSplitType=' + options.chartSplitType }
	if (options.statDivTop != null) { pars += '&statDivTop=' + options.statDivTop; }
	else if (jQuery("#chart-nav-stats") != null) { pars += '&statDivTop=' + jQuery("#chart-nav-stats").position().top; }
	
	// CALL TAB WITH NEW PARAMS
	var tabs = jQuery('#ppc').tabs();
	tabs.tabs( 'url', 3, url + "?" + pars);
	tabs.tabs('load', 3);
}
// RENDER VIDEO
Ppc.renderContentVideo = function(options) {
	var url = 'http://'+o.host+'/'+o.gameRoot+'/format/playerpop/video';
	
	// BUILD VIDEO PARAM
	if (options.navDivTop != null) { navDivTop = options.navDivTop; } else { navDivTop = jQuery("#pcVideoNavItems").position().top; }
	var pars = 'playerId=' + options.playerId + '&playerIdType=' + options.playerIdType + '&leagueId=' + options.leagueId + '&videoId=' + options.videoId + '&navDivTop=' + navDivTop;
	
	// CALL TAB WITH NEW PARAMS
	var tabs = jQuery('#ppc').tabs();
	tabs.tabs('select', 2);
	tabs.tabs('url', 2, url + "?" + pars);
	tabs.tabs('load', 2);
}
// VIDEO NAV
Ppc.videoNav = function(upDown, incomingTop) {
	var lineHeight = 24;
	var divHeight = jQuery("#pcVideoNavItems").height(); 
	var currentTop = jQuery("#pcVideoNavItems").position().top;
	
	// PAGINATE TO SELECTED STAT ROW
	if (incomingTop != null) { currentTop = incomingTop; }

	if (upDown == "up" && currentTop + lineHeight <= 0) { 
		var newTop = currentTop + lineHeight; 
	} else if (upDown == "down" && (currentTop - lineHeight)*-1 < divHeight) { 
		var newTop = currentTop - lineHeight; 
	} else {
		var newTop = currentTop; 
	}
	jQuery("#pcVideoNavItems").css({ top: newTop+'px' });
	
	// HIDE SHOW NAV ARROWS 
	var upArrowDisplay = "visible";
	var downArrowDisplay = "visible";
	if (newTop == 0) { upArrowDisplay = "hidden"; }
	if ((newTop * -1) + (lineHeight*2) >= divHeight) { downArrowDisplay = "hidden"; }
	jQuery("#videoNavUp").css({ visibility: upArrowDisplay });
	jQuery("#videoNavDown").css({ visibility: downArrowDisplay });
}
// RENDER NEWS
Ppc.renderContentNews = function(options) {
	var url = 'http://'+o.host+'/'+o.gameRoot+'/format/playerpop/news';
	
	// BUILD NEWS PARAM
	var pars = 'playerId=' + options.playerId + '&playerIdType=' + options.playerIdType + '&leagueId=' + options.leagueId + '&videoId=' + options.videoId;
	
	// CALL TAB WITH NEW PARAMS
	var tabs = jQuery('#ppc').tabs();
	tabs.tabs('select', 1);
	tabs.tabs('url', 1, url + "?" + pars);
	tabs.tabs('load', 1);
}
// OLD SCHOOL LINKS
Ppc.addToOldSchoolLinks = function() {
	var gameRoots = {};
	gameRoots['mlb'] = 'flb';
	gameRoots['nfl'] = 'ffl';
	gameRoots['nba'] = 'fba';
	gameRoots['nhl'] = 'fhl';
	
	var pattern = /http:\/\/.*espn\.go\.com\/(mlb|nfl|nba|nhl)\/players?\/.*(statsId|playerId|tickerId|id)(?:=|\/)([0-9]+)/;
	
	var numInserted = 0;
	var anchorTags = document.getElementsByTagName('a');
	for(var i=anchorTags.length-1; i>-1; --i) {
		if (anchorTags[i].href) {
			var matches = anchorTags[i].href.match(pattern);
			if (matches && matches.length > 3) {
				var gameRoot = gameRoots[matches[1]];
				var playerIdType = matches[2];
				var playerId = matches[3];

				if (playerIdType == 'playerId' || playerIdType == 'id') {
					playerIdType = 'sportsId';
				}

				if (gameRoot) {
					jQuery(anchorTags[i]).attr({
						'class': 'flexpop',
						'instance': '_ppc',
						'playerid': playerId,
						'playeridtype': playerIdType,
						'gameroot': gameRoot,
						'content': 'tabs#ppc',
						'tab': 'null',
						'fpopwidth': '490px',
						'fpopheight': '357px',
						'cache': 'true'
					});
					++numInserted;
				}
			}
		}
	}
	return numInserted;
}
/* end popPlayerCard */

/* start formatNumberTea */


function formatNumberTea(number, pattern) {
	if (isNaN(number)) {number = 0};
	var negativeSign = (number < 0) ? '-' : '';
	var formattedNumber;

	if (number == Infinity || number >= 17976931348623157000000000) {
		formattedNumber = 'INF';
	} else {
		var splitByDec = pattern.split('.');
		var patternL = splitByDec[0];
		var patternR = splitByDec[1] ? splitByDec[1] : '';

		splitByDec = (Math.round(Math.abs(number)*Math.pow(10,patternR.length))/Math.pow(10,patternR.length)+'').split('.');
		var numberL = (splitByDec[0] != '0' || patternL == '') ? splitByDec[0] : '';
		var numberR = splitByDec[1] ? splitByDec[1] : '';

		for (var l=0; l < patternL.length; ++l) {
			if (patternL.charAt(l) == '0' && numberL.length <= l) {
				numberL = '0' + numberL;
			}
		}

		for (var r=0; r < patternR.length; ++r) {
			if (patternR.charAt(r) == '0' && numberR.length <= r) {
				numberR+='0';
			}
		}

		var decimalPoint = (numberR === '') ? '' : '.';
		formattedNumber = numberL + decimalPoint + numberR;
	}
	return negativeSign + formattedNumber + '';
}
/* end formatNumberTea */

/* start flexpop */

/********************  FLEXPOP HOW TO  ********************
Add class="flexpop" to any link, div or image to apply the flexpop code
Add any of the following attributes to customize the flexpop: 
	- content: specify the content type ("iframe", "string", "inline", "tabs" or "ajax") followed a '#' and the content.
		iframe example: <a href="" content="iframe#http://www.google.com" class="flexpop">xxx</a>
		string example: <a href="" content="string#Just a simple string!" class="flexpop">xxx</a>
		ajax example: <a href="" content="ajax#/'gc.GAME_ROOT'/test/template_name" class="flexpop">xxx</a>
		inline example: <a href="" content="inline#name_of_div" class="flexpop">xxx</a>
		tabs example: <a href="" content="tabs#ppc">xxx</a> (tabs are built using format.flexpop.tabs())
	- style: 'modal' or 'help' styles
	- modal: set to 'true' to center the flexpop inside a modal overlay 
	- alert: set to 'true' to hide nav and, in the case of modal mode, clicking the overlay will not close the popup
	- tab: sets the default selected tab
	- cache: set to 'true' to turn on caching
	- fpopHeight: specified flexpop height, 'auto' by default
	- fpopWidth: specified flexpop width, 'auto' by default
***********************************************************/

// FLEX POPUP
var Flexpop = {};
// FLEXPOP INSTANCES
Flexpop.INSTANCES = [];
// FLEXPOP CONSTANTS
Flexpop.IMG_PATH_ARM = 'http://g.espncdn.com/s/fhllm/12/images/popup/';
Flexpop.TAB_HEIGHT = 36;
// ARM CONSTANTS
Flexpop.ORIENTATION_DOWN = 0;
Flexpop.ORIENTATION_UP = 1;
Flexpop.ORIENTATION_LEFT = 0;
Flexpop.ORIENTATION_RIGHT = 1;
Flexpop.ORIENTATION_CENTER = 2;
Flexpop.ARM_HEIGHT = null;
Flexpop.ARM_WIDTH = null;
// IS USER HOVERING ON FLEXPOP
Flexpop.isHover = false;
//IPAD DETECTION
Flexpop.isiPad = navigator.userAgent.match(/iPad/i) != null;

// INIT
Flexpop.init = function(linkInfo, e) {
	jQuery(linkInfo).live(e, function(event) {
		var jqry_this = jQuery(this);
		
		var fpopOpen = false;
		var pos = jqry_this.offset();
		var posW = jqry_this.width();
		var posH = jqry_this.height();
				
		var i =  jqry_this.attr("instance") || "_default";
		var clssArray = (jqry_this.attr("class")||"").split(' ');
		for (clss in clssArray) { if (clssArray[clss] == 'fpop_open' + i) { fpopOpen = true; } }
				
		if (!fpopOpen) {
			if (event.type == 'mouseout') { 
				Flexpop.remove(i);
			} else  {
				Flexpop.isHover = true; // KILL HOVER TIMER
				// FLEXPOP SETTINGS
				var a = jqry_this.href || jqry_this.alt;
				// SPLIT CONTENT FROM CONTENT TYPE
				var contentAttr = jqry_this.attr("content") || "";
				var c = contentAttr.substr(contentAttr.indexOf("#") + 1, contentAttr.length);
				var ct = contentAttr.substr(0, contentAttr.indexOf("#")) || 'ajax';
				var o = {
					instance: i,
					content: c,
					contentType: ct,
					style: jqry_this.attr("fpopStyle"),
					modal: jqry_this.attr("modal"),
					alert: jqry_this.attr("alert"),
					tab: jqry_this.attr("tab"),
					cache: jqry_this.attr("cache"),
					fpopHeight: jqry_this.attr("fpopHeight"),
					fpopWidth: jqry_this.attr("fpopWidth"),
					leagueId: jqry_this.attr("leagueId"),
					teamId: jqry_this.attr("teamId"),
					playerId: jqry_this.attr("playerId"),
					playerIdType: jqry_this.attr("playeridtype"),
					gameRoot: jqry_this.attr("gameroot"),
					xOrient: jqry_this.attr("xorient"),
					pos: pos,
					posW: posW,
					posH: posH,
					pageX: event.pageX,
					pageY: event.pageY
				};
				// REMOVE ANY OPEN FLEXPOP INSTANCES
				if (o.modal == "true") { Flexpop.remove_all(); }
				else { Flexpop.remove(o.instance); }
				// ADD OPEN FLEXPOP INSTANCE
				jqry_this.addClass("fpop_open" + o.instance);
				// SHOW FLEXPOP
				Flexpop.show(o);
			}
		} else {	// CLOSE FLEXPOP INSTANCE IF ALREADY OPEN
			if (event.type == 'mouseout') {	// KEEP FLEXPOP HOVER ISTANCE OPEN WHILE USER IS HOVERING ON THE FLEXPOP WINDOW
				Flexpop.isHover = false;
				jQuery('#fpop_window' + i).hover (
					function() {  Flexpop.isHover = true; },
					function () { Flexpop.remove(i); } );				
					setTimeout(function() { if (!Flexpop.isHover) { Flexpop.remove(i); } }, 500);
			} else {
				Flexpop.remove(i);
			}
			return false;
		}		
		return false;
	});
}
// DEFAULTS
Flexpop.defaults = function(o) {
	var options = {
		instance: o.instance || "_default",
		content: o.content,
		contentType: o.contentType || "ajax",
		style: o.style || "default",
		modal: o.modal || null,	
		alert: o.alert  || null,
		tab: o.tab || 0,
		cache: o.cache || null,
		fpopHeight: o.fpopHeight || "auto",
		fpopWidth: o.fpopWidth || "auto",
		leagueId: o.leagueId || -1,
		teamId: o.teamId || -1,
		playerId: o.playerId || null,
		playerIdType: o.playerIdType || 'playerId',
		host: "games.espn.go.com",
		gameRoot: o.gameRoot || 'fhl',
		pos: o.pos || null,
		posW: o.posW || null,
		posH: o.posH || null,
		pageX: o.pageX || null,
		pageY: o.pageY || null,
		xOrient: o.xOrient || null
	}	
	return options;
}
// SHOW
Flexpop.show = function(options) {
	// GET DEFAULT OPTIONS
	o = Flexpop.defaults(options);	
	// SET INSTANCE
	Flexpop.instance_set(o.instance);
	// GET CACHED DATA
	cachedData = Flexpop.cache_get(o);
	// CREATE FLEX POP WINDOW
	if (o.modal == "true") { // MODAL
		jQuery("body").append('<div id="fpop_overlay' + o.instance + '" class="fpop_overlay"></div><div id="fpop_window' + o.instance + '" class="fpop_window_modal '+o.gameRoot+'"></div>');
		jQuery("body").css("overflow","hidden");
		if (o.alert != 'true') { jQuery('#fpop_overlay' + o.instance).click(function () { Flexpop.remove_all() }); }
	} else { 
		jQuery("body").append('<div id="fpop_window' + o.instance + '" class="fpop_window '+o.gameRoot+'"></div>'); 
	}
	// DISPLAY CONTENT
	var track = true;
	Flexpop.shell_build(o);
	if (o.contentType == "tabs") {	// TABS
		track = false;
		jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '" style="width:' + o.fpopWidth + ';height:' + o.fpopHeight + ';"></div>');
		Flexpop.nav_add(o);
		Flexpop.position(o);
		Flexpop.tab_add(o);
		setTimeout(function() {	jQuery('div#fpop_window' + o.instance).show();}, 500); // ALLOW TAB CONTENT TIME TO LOAD
	} else if (o.contentType == "iframe") {	// IFRAME CONTENT
		if (cachedData === undefined) {
			jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '"><iframe frameborder="no" scorling="no" hspace="0" style="width:' + o.fpopWidth + ';height:' + o.fpopHeight + '; background-color:#FFFFFF;" src="' + o.content + '" id="fpop_iframeContent' + o.instance + '"></iframe>');
			Flexpop.cache_set(o);
		} else {
			jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '">' + cachedData + '</div>');
		}
		Flexpop.nav_add(o);
		Flexpop.position(o);
		jQuery('div#fpop_window' + o.instance).show();
	} else if (o.contentType == "inline") {	// INLINE CONTENT
		jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '" style="width:' + o.fpopWidth + ';height:' + o.fpopHeight + ';"></div>');
		Flexpop.nav_add(o)

		if (cachedData === undefined) {
			contentId = "#" + o.content;
			jQuery('#fpop_content' + o.instance).append(jQuery(contentId).children());
			jQuery('#fpop_window' + o.instance).unload(function () {
				jQuery(contentId).append(jQuery('#fpop_content' + o.instance).children());
			});
			Flexpop.cache_set(o);
		} else {
			jQuery('#fpop_content' + o.instance).append(cachedData);
		}
		
		Flexpop.position(o);
		jQuery('div#fpop_window' + o.instance).show();
	} else if (o.contentType == "string") {	// STRING CONTENT
		jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '" style="width:' + o.fpopWidth + ';height:' + o.fpopHeight + ';"></div>');
		Flexpop.nav_add(o)
		
		if (cachedData === undefined) {	
			jQuery('#fpop_content' + o.instance).append(o.content);
			Flexpop.cache_set(o);
		} else { 
			jQuery('#fpop_content' + o.instance).append(cachedData);
		}		
		Flexpop.position(o);
		jQuery('div#fpop_window' + o.instance).show();	
	} else {	// AJAX CONTENT
		jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_content' + o.instance + '" class="fpop_content_' + o.style + '" style="width:' + o.fpopWidth + ';height:' + o.fpopHeight + ';"></div>');
		Flexpop.nav_add(o);
		if (cachedData === undefined || cachedData === null) {
			jQuery('#fpop_content' + o.instance).load(o.content,function() {
				Flexpop.position(o);
				jQuery('div#fpop_window' + o.instance).show();
				Flexpop.cache_set(o);
			});			
		} else {
			jQuery('#fpop_content' + o.instance).append(cachedData);
			Flexpop.position(o);
			jQuery('div#fpop_window' + o.instance).show();
		}
	}
	
	// REMOVE
	jQuery('#fpop_closebtn').live('click', function () { 
		i = "" + jQuery(this).attr("instance");
		c = "" + jQuery(this).attr("class");
		
		if (c == "fpop_closebtn_modal") { Flexpop.remove_all(); }
		else { Flexpop.remove(i); }
		return false;
	});
	
	if (track) {
		Flexpop.tracking(o);
	}
		
	return false;
}
// REMOVE
Flexpop.remove = function(instance) {
	if (instance === undefined) { instance = "_default"; }

	if (jQuery('div#fpop_overlay' + instance).length != 0) { jQuery("body").css("overflow","auto") };
	jQuery('div#fpop_overlay' + instance).remove();
	jQuery('div#fpop_window' + instance).remove();
	jQuery(".fpop_open" + instance).removeClass("fpop_open" + instance);
	
	return false;
}
// REMOVE ALL FLEXPOP INSTANCES
Flexpop.remove_all = function() {
	for (var i=0; i < Flexpop.INSTANCES.length; ++i) {
		Flexpop.remove(Flexpop.INSTANCES[i]);
	}
}
// ADD NAV
Flexpop.nav_add = function(o) {
	if (o.alert != 'true') { // DO NOT DISPLAY NAV BAR WHILE IN ALERT MODE
		if (o.style == "modal") {
			jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_nav_modal' + o.instance + '" class="fpop_nav_modal"><a href="#" title="" id="fpop_closebtn" class="fpop_closebtn_modal" instance="' + o.instance + '" style="color:#9C9A9C;">X</a></div>');
		} else if (o.style == "help") { 
			// NO HELP NAV
		} else  { // DEFAULT NAV BAR
			// INSERT POP PLAYER CARD AD
			var ad = '';
			if (false && o.instance == '_ppc' && o.fpopWidth == '490px') {
				ad = '<iframe style="float:left;" src="/' + o.gameRoot + '/format/adFrame?pageName=playercards&context=&iType=playercardlogo&width=350&height=30&zone=' + o.gameRoot + 'playercards&adSegments=' + espn.core.ad_segments() + '" width="350" height="30" scrolling="no" frameborder="0" marginheight="0" marginwidth="0" allowtransparency="true"></iframe>';
			}
			jQuery('#fpop_content_border' + o.instance).append('<div id="fpop_nav' + o.instance + '" class="fpop_nav">'+ad+'<img width="71" height="20" border="0" title="" alt="CLOSE" src="http://g.espncdn.com/s/flblm/10/images/design07/playerpop/close.gif" id="fpop_closebtn" class="fpop_closebtn" instance="' + o.instance + '"></div>');
		}
	}
}
// ADD ARM
Flexpop.arm_add = function(o, orientation) {
	if (o.style == 'help') {
		imagePath = 'pcArrow_help';
		if(o.xOrient != "right") {
			jQuery('#fpop_window' + o.instance).append('<div id="fpop_arm' + o.instance + '" width="' + Flexpop.ARM_WIDTH + '" height="' + Flexpop.ARM_HEIGHT + '" style="z-index: 2; position: absolute;"></div>');
			jQuery('#fpop_arm' + o.instance).append('<img id="fpop_arm_image' + o.instance + '" width="' + Flexpop.ARM_WIDTH + '" height="' + Flexpop.ARM_HEIGHT + '" src="' + Flexpop.IMG_PATH_ARM + imagePath + '.gif">');
		}
	} else {
		imagePath = 'pcArrow_' + orientation.x;
		jQuery('#fpop_window' + o.instance).append('<div id="fpop_arm' + o.instance + '" width="' + Flexpop.ARM_WIDTH + '" height="' + Flexpop.ARM_HEIGHT + '" style="z-index: 2; position: absolute;"></div>');
		if (orientation.y == Flexpop.ORIENTATION_CENTER) { imagePath = imagePath + Flexpop.ORIENTATION_UP; } else { imagePath = imagePath + orientation.y; }
		jQuery('#fpop_arm' + o.instance).append('<img id="fpop_arm_image' + o.instance + '" width="' + Flexpop.ARM_WIDTH + '" height="' + Flexpop.ARM_HEIGHT + '" src="' + Flexpop.IMG_PATH_ARM + imagePath + '.png">');
	}
}
// SET ARM DIMENSIONS
Flexpop.arm_set_dimensions = function(o) {
	if (o.style == 'help') {
		Flexpop.ARM_HEIGHT = 11;
		Flexpop.ARM_WIDTH = 10;
	} else {
		Flexpop.ARM_HEIGHT = 110;
		Flexpop.ARM_WIDTH = 59;
	}
}
// ADD TABS
Flexpop.tab_add = function(o) {
	// SELECT TAB CONTENT
	var content = '';
	if (o.content == "ppc") {
		content = '<div id="ppc">' +
			'<ul>' +
			'<li class="ui-tabs-nav-li"><table class="fpop_tab_table" cellpadding="0" cellspacing="0"><tr><td class="fpop_tab_left"></td><td class="fpop_tab_center"><a href="http://'+o.host+'/'+o.gameRoot+'/format/playerpop/overview?leagueId=' + o.leagueId + '&playerId=' + o.playerId + '&playerIdType=' + o.playerIdType + '">OVERVIEW</a></td></tr></table></li>' +
			'<li class="ui-tabs-nav-li"><table class="fpop_tab_table" cellpadding="0" cellspacing="0"><tr><td class="fpop_tab_left"></td><td class="fpop_tab_center"><a href="http://'+o.host+'/'+o.gameRoot+'/format/playerpop/news?leagueId=' + o.leagueId + '&playerId=' + o.playerId + '&playerIdType=' + o.playerIdType + '">NEWS</a></td></tr></table></li>' +
			'<li class="ui-tabs-nav-li"><table class="fpop_tab_table" cellpadding="0" cellspacing="0"><tr><td class="fpop_tab_left"></td><td class="fpop_tab_center"><a href="http://'+o.host+'/'+o.gameRoot+'/format/playerpop/video?leagueId=' + o.leagueId + '&playerId=' + o.playerId + '&playerIdType=' + o.playerIdType +'">VIDEO</a></tr></table></li>';
		if (o.leagueId && o.leagueId > 0) {
			content += 
			'<li class="ui-tabs-nav-li"><table class="fpop_tab_table" cellpadding="0" cellspacing="0"><tr><td class="fpop_tab_left"></td><td class="fpop_tab_center" id="fpop_ppc_charts_tab_link"><a href="http://'+o.host+'/'+o.gameRoot+'/format/playerpop/charts?leagueId=' + o.leagueId + '&playerId=' + o.playerId + '&playerIdType=' + o.playerIdType +'">CHARTS</a></tr></table></li>' +
			'<li class="ui-tabs-nav-li"><table class="fpop_tab_table" cellpadding="0" cellspacing="0"><tr><td class="fpop_tab_left"></td><td class="fpop_tab_center"><a href="http://'+o.host+'/'+o.gameRoot+'/format/playerpop/transactions?leagueId=' + o.leagueId + '&playerId=' + o.playerId + '&playerIdType=' + o.playerIdType + '">TRANSACTIONS</a></td></tr></table></li>';
		}
		content +='</ul></div>';
	}
	
	// ADD TABS
	jQuery('#fpop_content' + o.instance).append(content);
 	jQuery('#'+o.content).tabs({
 		selected: parseInt(o.tab),
 		cache: o.cache,
 		ajaxOptions: { crossDomain: jQuery.support.cors ? undefined : false }, /* otherwise the request is aborted in IE */
 		show: function(){ Flexpop.tracking(o); }
 	});
	jQuery('#fpop_td_tab' + o.instance).append(jQuery('.ui-tabs-nav'));

}
// BUILD SHELL
Flexpop.shell_build = function(o) {
	if (o.style == "modal") {
		jQuery('#fpop_window' + o.instance).append('<div id="fpop_modal_border' + o.instance + '" class="fpop_modal_border"><div id="fpop_content_border' + o.instance + '"></div></div>');
	} else if (o.style == "help") { 
		jQuery('#fpop_window' + o.instance).append('<div id="fpop_help_border' + o.instance + '" class="fpop_help_border"><div id="fpop_content_border' + o.instance + '"></div></div>');
	} else {
		tabClass = "fpop_corner_topright_notabs";
		if (o.contentType == "tabs") { tabClass = "fpop_corner_topright_tabs" }; // DO NOT ROUND TOP RIGHT CORNER WHEN USING TABS 
		
		jQuery('#fpop_window' + o.instance).append('<table style="border-collapse: collapse;" cellspacing="0" cellpadding="0">' +
			'<tr><td id="fpop_td_tab' + o.instance + '" colspan="3"></td></tr>' +
			'<tr>' +
			'<td><div class="fpop_corner_topleft"></div></td>' +
			'<td class="fpop_border_top"></td>' +
			'<td><div class="' + tabClass + '"></div></td>' +
			'</tr>' +
			'<tr>' +
			'<td class="fpop_border_left"></td>' +
			'<td><div id="fpop_content_border' + o.instance + '"></div></td>' +
			'<td class="fpop_border_right"></td>' +
			'</tr>' +
			'<tr>' +
			'<td><div class="fpop_corner_bottomleft"></div></td>' +
			'<td class="fpop_border_bottom"></td>' +
			'<td><div class="fpop_corner_bottomright"></div></td>' +
			'</tr>'	+
			'</table>');
	}
}
// GET ORIENTATION
Flexpop.orientation = function(o, positions) {
	if (o.style == 'help') {
		var xOrientation = Flexpop.ORIENTATION_LEFT
		if(o.xOrient == "right") xOrientation = Flexpop.ORIENTATION_RIGHT;
		ao = {y: Flexpop.ORIENTATION_UP, x: xOrientation}
	} else {
		var widthNeeded = jQuery('#fpop_window' + o.instance).width() + Flexpop.ARM_WIDTH + 30;
		var heightNeeded = jQuery('#fpop_window' + o.instance).height();

		if (o.contentType == "tabs") {
			widthNeeded = parseInt(o.fpopWidth) + Flexpop.ARM_WIDTH + 30;
			heightNeeded = parseInt(o.fpopHeight) + Flexpop.TAB_HEIGHT + 50;
		}

		var availableHeight = jQuery(window).height();
		var availableWidth = jQuery(window).width();
				
		// LEFT | RIGHT
		if (availableWidth - (positions.right - (jQuery(window).scrollLeft() || document.body.scrollLeft)) - widthNeeded > 0) {
			x_orientation = Flexpop.ORIENTATION_LEFT;
		} else if ((positions.left - (jQuery(window).scrollLeft() || document.body.scrollLeft)) > widthNeeded) {
			x_orientation = Flexpop.ORIENTATION_RIGHT;
		} else {
			x_orientation = Flexpop.ORIENTATION_CENTER;
		}
		// UP | DOWN
		if ((positions.top - (jQuery(window).scrollTop() || document.body.scrollTop)) > heightNeeded) {
			y_orientation = Flexpop.ORIENTATION_DOWN;
		} else if (availableHeight - (positions.bottom - (jQuery(window).scrollTop() || document.body.scrollTop)) - heightNeeded > 0) {
			y_orientation = Flexpop.ORIENTATION_UP;
		} else {
			y_orientation = Flexpop.ORIENTATION_CENTER;
		}

		ao = {y: y_orientation, x: x_orientation};
	}
	return ao;
}
// POSITION WINDOW / ARM
Flexpop.position = function(o) {
	if (o.style == 'modal') {
		var h = jQuery('#fpop_window' + o.instance).height() || 0;
		var w = jQuery('#fpop_window' + o.instance).width() || 0;
		jQuery('#fpop_window' + o.instance).css({top: (jQuery(window).height() - h) / 2 + "px", left: ( jQuery(window).width() - w) / 2 + "px"});
	} else {
		var windowX;
		var windowY;
		var armX;
		var armY;
		
		Flexpop.arm_set_dimensions(o);
		positions = Flexpop.element_position(o);
		orntn = Flexpop.orientation(o, positions);
		
		// ADD ARM		
		Flexpop.arm_add(o, orntn);
		
		// UP | DOWN
		if (orntn.y == Flexpop.ORIENTATION_DOWN) {
			armY = jQuery('#fpop_window' + o.instance).height() - Flexpop.ARM_HEIGHT;
			windowY = positions.top - jQuery('#fpop_window' + o.instance ).height();
		} else if (orntn.y == Flexpop.ORIENTATION_UP) {
			armY = 0;
			windowY = positions.bottom;
		} else {	// ORIENTATION_CENTER
			windowY = (jQuery(window).scrollTop() || document.body.scrollTop) + ((document.documentElement.clientHeight - jQuery('#fpop_window' + o.instance ).height()) / 2);
			armY = positions.top - windowY;
			if (armY > (document.documentElement.clientHeight / 2)) {
				imagePath = Flexpop.IMG_PATH_ARM + 'pcArrow_' + orntn.x + Flexpop.ORIENTATION_DOWN + '.png';
				jQuery('#fpop_arm_image' + o.instance).attr('src', imagePath);
				armY = armY - Flexpop.ARM_HEIGHT;
			}
		}
		// LEFT | RIGHT
		if (orntn.x == Flexpop.ORIENTATION_LEFT) {
			armX = (-1 * Flexpop.ARM_WIDTH) + 2;
			windowX = positions.right + Flexpop.ARM_WIDTH;
		} else if (orntn.x == Flexpop.ORIENTATION_RIGHT) {
			armX = jQuery('#fpop_window' + o.instance).width() - 10;
			windowX = positions.left - (jQuery('#fpop_window' + o.instance).width() + Flexpop.ARM_WIDTH - 10);
		} else {	// ORIENTATION_CENTER
			windowX = 0;
		}
		
		// POSITION WINDOW
		jQuery('#fpop_window' + o.instance).css({ top: windowY +'px', left: windowX +'px' })
		// POSITION ARM
		if (o.style == 'help') {
			jQuery('#fpop_arm' + o.instance).css({ top: '-4px', left: '-4px' });
		} else {	// DEFAULT
			if (armX == null) { jQuery('#fpop_arm' + o.instance).css({ display: 'none' }); }
			else { jQuery('#fpop_arm' + o.instance).css({ top: armY +'px', left: armX +'px' }); }
		}
	}
}
// GET ELEMENT POSITION
Flexpop.element_position = function(o) {
	// SPECIAL POSITIONING FOR iPad and COMPARE PLAYERS
	if (Flexpop.isiPad) {
		var elementLeft = o.pos.left;
		var elementRight = o.pos.left + o.posW;
		var elementTop = o.pageY;
		var elementBottom = o.pageY;
	} else if (jQuery('#comparePlayersTable').length != 0) {
		var elementLeft = o.pageX;
		var elementRight = o.pageX;
		var elementTop = o.pageY;
		var elementBottom = o.pageY;
	} else {
		var elementLeft = o.pos.left;
		var elementRight = o.pos.left + o.posW;
		var elementTop = o.pos.top;
		var elementBottom = o.pos.top + o.posH;
	}
	ePos = {left: elementLeft, right: elementRight, top: elementTop, bottom: elementBottom };
	return ePos;
}
// GET CACHED DATA
Flexpop.cache_get = function(o) {
	if (o.cache == "true") {
		return jQuery("body").data(o.content);
	} else { return undefined; }
}
// SET CACHED DATA
Flexpop.cache_set = function(o) {
	if (o.cache == "true") {
		jQuery("body").data(o.content, jQuery('#fpop_content' + o.instance).html());
	} else { return undefined; }
}
// SET INSTANCE
Flexpop.instance_set = function(instance) {
	var newInstance = true;
	for (var i=0; i < Flexpop.INSTANCES.length; ++i) {
		if (Flexpop.INSTANCES[i] == instance) {
			newInstance = false;
		}
	}
	if (newInstance) {
		Flexpop.INSTANCES.push(instance);
	}
}
// PAGE TRACKING
Flexpop.tracking = function(o) {
	if (!window.anTrackPageView) {
		return false;
	}
	var pageName = o.instance;
	if (pageName == "_default") {
		/* don't bother tracking what we won't be able to disambiguate */
		return false;
	}
	if (o.contentType == "tabs") {
		var tabId = "#" + o.content;
		var selected = jQuery(tabId).tabs('option', 'selected') + 1;
		pageName = pageName + '-' + jQuery('.ui-tabs-selected a').html();
	}
	var anExec;
	var anSiteSection = 'fantasy';
	var anContentSection = (s_omni && s_omni.channel ? s_omni.channel : '');
	var anContentSubSubSection = 'fhl';
	var anContentSubSection = 'hockey';
	var anContentType = 'flexpop'
	var anLeafPageName = 'flexpop-' + pageName;
	var anStoryId = null;
	anTrackPageView(anExec,anSiteSection,anContentSection,anContentSubSection,anContentSubSubSection,anContentType,anLeafPageName,anStoryId);
}

Flexpop.isShowing = function(instance) {
	if (!instance) { instance = "_default"; }
	return jQuery("#fpop_window"+instance).is(":visible");
};

jQuery(document).ready(function(){
	Ppc.addToOldSchoolLinks();
	Ppc.escClose();
	Flexpop.init('.flexpop', 'click');
	Flexpop.init('.flexpop_hover', 'mouseover mouseout');
});
/* end flexpop */

