/*************************** START CONFIGURATION SECTION ******************************/
/*
 example below has one filter for all ads on the draft 2009 tracker page that are in slot rightrailfirst
 and another for all ads across the entire news section.

 !!! do not remove example below, other people may need this :D !!!


	var n_internal_ads		= [
		               		[{type:'url',match:'/draft/2009/tracker'},{type:'slot',match:'rightrailfirst'}],
		               		[{type:'section',match:'/news'}]
	];

*/
/**************************** END CONFIGURATION SECTION *******************************/

/**
 * ****************************** START LIB SECTION
 * **********************************
 */
Date.ET_OFFSET = -5 * 60 * 60 * 1000; // milliseconds behind GMT for ET
// JS version of Ruby on Rails' distance_of_time_in_words
Date.distance_of_time_in_words = function (from_time, to_time, include_s) {
	var include_seconds, distance_in_minutes, distance_in_seconds;
	include_seconds = include_s || false;
	distance_in_minutes = Math.round(Math.abs(to_time - from_time) / 60000);
	distance_in_seconds = Math.round(Math.abs(to_time - from_time) / 1000);
	if (distance_in_minutes < 2) {
		if (include_seconds) {
			if (distance_in_seconds < 5) { return 'less than 5 seconds'; }
			if (distance_in_seconds < 10) { return 'less than 10 seconds'; }
			if (distance_in_seconds < 20) { return 'less than 20 seconds'; }
			if (distance_in_seconds < 40) { return 'half a minute'; }
			if (distance_in_seconds < 59) { return 'almost a minute'; }
			return '1 minute';
		}
		return (distance_in_minutes === 0) ? 'less than a minute' : '1 minute';
	}
	if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes'; }
	if (distance_in_minutes < 89) { return 'about 1 hour'; }
	if (distance_in_minutes < 1439) { return 'about ' + Math.round(distance_in_minutes / 60) + ' hours'; }
	if (distance_in_minutes < 2879) { return '1 day'; }
	if (distance_in_minutes < 43199) { return Math.round(distance_in_minutes / 1440) + ' days'; }
	if (distance_in_minutes < 86399) { return 'about 1 month'; }
	if (distance_in_minutes < 525599) { return Math.round(distance_in_minutes / 43200) + ' months'; }
	if (distance_in_minutes < 1051199) { return 'about 1 year'; }
	return 'over ' + Math.round(distance_in_minutes / 525600) + ' years';
};
Object.extend(Date.prototype, {
	/**
	 * Returns the current month in AP Style
	 */
	getAPStyleMonth: function() {
		switch(this.getMonth()) {
			case  0: return 'Jan.';
			case  1: return 'Feb.';
			case  2: return 'March';
			case  3: return 'April';
			case  4: return 'May';
			case  5: return 'June';
			case  6: return 'July';
			case  7: return 'Aug.';
			case  8: return 'Sept.';
			case  9: return 'Oct.';
			case 10: return 'Nov.';
			case 11: return 'Dec.';
		}
	},
	/**
	 * Returns the current time in AP Style
	 */
	getAPStyleTime: function(_includeSeconds) {
		var h, m, a, s = '';
		h = this.getHours();
		a = (h > 11) ? ' p.m.' : ' a.m.';
		if (h === 0 && ! _includeSeconds) { return 'midnight'; }
		else if (h === 0) { h = 12;}
		else if (h === 12 && ! _includeSeconds) { return 'noon';}
		else if (h > 12) { h -= 12;}
		m = this.getMinutes();
		m = (m === 0 && ! _includeSeconds) ? '' :
		    (m < 10) ? ':0' + m :
		    ':' + m;
		if (_includeSeconds) {
			s = this.getSeconds();
			s = (s < 10) ? ':0' + s : ':' + s;
		}
		return h + m + s + a;
	},
	/**
	 * Converts the current date to the equivalent time in ET.
	 */
	toET: function() {
		return new Date( this.getTime() + this.getTimezoneOffset() * 60000 + Date.ET_OFFSET );
	},
	/**
	 * Converts a date to its string representation in AP Style, ET.
	 */
	toAPStyle: function( _includeTime, _includeSeconds ) {
		var etDate = this.toET();
		return etDate.getAPStyleMonth() + ' ' + etDate.getDate() + ', ' + etDate.getFullYear() + ( ( _includeTime ) ? ' at ' + etDate.getAPStyleTime(_includeSeconds) : '' );
	},
	/**
	 * Returns the full name of the date's day.
	 */
	getDayName: (function(){
		var NAMES = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
		return function() { return NAMES[this.getDay()]; };
	}()),
	/**
	 * Returns the time since this date in English
	 */
	time_ago_in_words: function (include_seconds) {
		var now, direction;
		now = new Date();
		direction = (now - this > 0) ? ' ago' : ' from now';
		return Date.distance_of_time_in_words(this, now, include_seconds) + direction;
	}
});
Object.extend(String.prototype,{
	similarColor: function(c1){
		var v1		= this;
		var v2		= c1;
		if(this.indexOf('#') !== -1 || arguments[0].indexOf("#") !== -1){
			/* has hex hash sign, strip em */
			v1	= v1.replace('#','');
			v2	= v2.replace('#','');
		}
		if(this.indexOf('rgb') !== -1 && arguments[0].indexOf("rgb") !== -1){
			/* has rgb values */
		}
		// if((v1.length !== 6 || v2.length !== 6) && v){ return false; }
		var tol		= 78;
		var c0 		= (v1.indexOf('0x') > -1)?{'r':(parseInt(v1.substring(2,4), 16)),'g':(parseInt(v1.substring(4,6), 16)),'b':(parseInt(v1) & 0xff)}:{'r':(parseInt(v1.substring(1,3), 16) >> 16),'g':(parseInt(v1.substring(3,5), 16) >> 8),'b':(parseInt(v1.substring(5,7), 16))};
		var c1 		= (v2.indexOf('0x') > -1)?{'r':(parseInt(v2.substring(2,4), 16)),'g':(parseInt(v2.substring(4,6), 16)),'b':(parseInt(v2) & 0xff)}:{'r':(parseInt(v2.substring(1,3), 16) >> 16),'g':(parseInt(v2.substring(3,5), 16) >> 8),'b':(parseInt(v2.substring(5,7), 16))};
		var d 		= {'r':(Math.abs(c0.r - c1.r)),'g':(Math.abs(c0.g - c1.g)),'b':(Math.abs(c0.b - c1.b))}
		console.info('similarColors: ',c0,c1,d);
		if ( (d.r + d.g < tol && d.r + d.b < tol) || (d.r + d.g < tol && d.b + d.g < tol) || (d.r + d.b < tol && d.b + d.g < tol)) {
			// console.log('similarColor: returning true for '+v1+'
			// '+v2+'\n\r'+(d.r + d.g < tol && d.r + d.b < tol)+'\n\r'+(d.r +
			// d.g < tol && d.b + d.g < tol)+'\n\r'+(d.r + d.b < tol && d.b +
			// d.g < tol));
			return true
		}
		// console.log('similarColor: returning false for '+v1+'
		// '+v2+'\n\r'+(d.r + d.g < tol && d.r + d.b < tol)+'\n\r'+(d.r + d.g <
		// tol && d.b + d.g < tol)+'\n\r'+(d.r + d.b < tol && d.b + d.g < tol));
		return false
	}
});
Element.addMethods({
	getOuterHTML: function(element){ if(element.outerHTML){ return element.outerHTML}; var parent = element.parentNode; var el = document.createElement(parent.tagName); el.appendChild(element);var shtml = el.innerHTML; parent.appendChild(element); return shtml;},
	templatize: (function(){
		var FIND = /#%7B([^%]+)%7D/g, REPLACE = "#{$1}", ERROR = 'Could not templatize element ', EMPTY = "",
		    DATA_RE = / data\-(href|src|action|style)="([^"]*)"/g, DATA_REPLACE = ' $1="$2"';
		return function( _ref, _hide ) {
			var el, t, html, tempHTML;
			el = $(_ref);
			if (! el) { throw( ERROR + _ref ); }
			html = el.innerHTML.replace( FIND, REPLACE ).replace(DATA_RE, DATA_REPLACE);
			t = new Template( html );
			if ( false !== _hide ) {
				el.update( EMPTY );
				el.hide();
			}
			return t;
		};
	})(),
	text: function(el) {
		return el.innerText || el.textContent;
	}
});
Object.extend(Number.prototype, {
	commaify: (function() {
		var FIND    = /(\d)(\d{3}(?:,\d{3})*(?:\.\d+)?)$/,
		    REPLACE = "$1,$2";

		return function() {
			var workingString, selfAsString = this.toString();

			while (workingString !== selfAsString) {
				workingString = selfAsString;
				selfAsString  = selfAsString.replace(FIND, REPLACE);
			}
			return selfAsString;
		};
	}()),
	pluralEnding: function() { return (this - 1 === 0) ? '' : 's'; } // this === 1 -> false
});
Math.randomByTime = function(){ var time, d; d = new Date(); d.setSeconds(Math.floor(d.getUTCSeconds() / 10) * 10); d.setMilliseconds(0); time = d.getTime(); return time };
String.prototype.truncateAtLastWord = function(intLength){try{var tStr = (new String(this)).truncate(intLength);if(tStr.endsWith('...')){return (new String(this)).truncate(((tStr.lastIndexOf(' ')+1)+3));}else{return this;}}catch(e){nfl.log(e.message)}}
Object.extend(Prototype.Browser,{Version: (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1], Chrome: navigator.userAgent.toLowerCase().match(/chrome/), IPhone: navigator.userAgent.toLowerCase().indexOf('iphone;') > -1, PalmPre: navigator.userAgent.toLowerCase().indexOf('webos/') > -1, Android: navigator.userAgent.toLowerCase().indexOf('android') > -1 });
Function.prototype.defaults = function(origArgs) { for (var i = 0, j = 1; j < arguments.length; i++, j++) { if (typeof origArgs[i] == 'undefined') origArgs[i] = arguments[j];}}
Object.extend(document, {
	cookies: function(){
		return {
			getValue: function(offset){ var endstr = document.cookie.indexOf (";", offset); if (endstr == -1){endstr = document.cookie.length;}; return unescape(document.cookie.substring(offset, endstr));},
			get: function(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) { return document.cookies.getValue(j); }; i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return "";},
			set: function(name, value, expires, path, domain, secure) { document.cookie = name + "=" + escape (value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");},
			remove: function(name,path,domain) { if (document.cookies.get(name)) { document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";}},
			getExipiry: function(days, hours, minutes) {var expDate = new Date( ); if(typeof days == "number" && typeof hours == "number" && typeof hours == "number") {expDate.setDate(expDate.getDate( ) + parseInt(days));expDate.setHours(expDate.getHours( ) + parseInt(hours));expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));return expDate.toGMTString( );}}
		}
	}(),
	insertAfter: function(new_node, existing_node){try{if(existing_node.next()){ existing_node.parentNode.insertBefore(new_node,existing_node.next());}else{ existing_node.parentNode.appendChild(new_node); }}catch(err){console.log("insertAfter Error: "+ err.message);}},
	include: function(path){var curScriptsRoot=""; var curScriptName=path; curScriptName='imported-js-'+ curScriptName.substring(curScriptName.lastIndexOf('/')+1,curScriptName.lastIndexOf('.js')).replace('.','-'); if(path.indexOf('http://') === -1){	var curScripts = document.getElementsByTagName("script"); for(s=1;s<curScripts.length;s++){try{ if(curScripts[s].src !== ''){ var curScriptsRootTemp = (curScripts[s].src); if(curScriptsRootTemp.indexOf("/scripts")){ curScriptsRoot = curScriptsRootTemp; curScriptsRoot = curScriptsRoot.substring(0,curScriptsRoot.indexOf("/scripts")); break; }}}catch(e){}}}; var headEle	= document.getElementsByTagName("head")[0]; var scriptEle = document.createElement('script'); scriptEle.id = curScriptName; scriptEle.type = 'text/javascript'; scriptEle.src = (curScriptsRoot + path); headEle.appendChild(scriptEle);}
});
/*
 * Creates a cross-browser "window:hashchange" event using the document object,
 * listens for native support for the hashchange event and uses that. Otherwise,
 * it checks for hash change at a standard interval.
 *
 * The `memo` property of the event is the results of calling
 * window.location.hashparams.get()
 *
 * usage: document.observe('window:hashchange',func);
 */
(function() {
	var hashChecker;
	function fireHashChangeEvent(event) {
		var hashHash = window.location.hashparams.get();
		document.fire('window:hashchange', hashHash ? hashHash.toObject() : {});
	}
	function checkHashChange(event) {
		try {
			Event.stopObserving(window, 'hashchange', checkHashChange);
			Event.observe(window, 'hashchange', fireHashChangeEvent);
			clearInterval(hashChecker);
			fireHashChangeEvent(event);
		} catch(e) {}
	}
	function hasHashChanged() {
		if(window.__hash == location.hash){ return; }
		window.__hash = location.hash;
		fireHashChangeEvent();
	}
	Event.observe(window, 'hashchange', checkHashChange);
	try {
		window.__hash = location.hash;
		hashChecker = setInterval(hasHashChanged, 100);
	} catch(e) {}
})();
window.location.hashparams = function(){
	return {
		getStringFromHash: function(oHash){
			var retStr = '';//, hashObj = $H(oHash);
			hashObj = $H(oHash);
			//retStr	= Object.toQueryString(hashObj).replace(/&/gi,'/').replace(/=/g,':');
			retStr	= (hashObj.toJSON().replace(/("| )/gi,'').replace(/,/gi,'/')); retStr	= retStr.substring(1,retStr.length - 1);
			/*
			hashObj.each(function(pair){
				if(hashObj.keys().sort().indexOf(pair.key) > -1){
					if(pair.key != pair.value){
						retStr += (pair.key+':'+pair.value +'/');
					}else{
						retStr += (pair.value +'/');
					}
				}
			});
			*/
			//console.log('getStringFromHash returning '+retStr);
			return retStr
			//return (retStr.substring(0,retStr.length - 1));
		},
		getHashFromString: function(stringObj){
			// nfl.log("getHashFromString: type of stringObj = "+(typeof
			// stringObj));
			if(stringObj.strip() == ''){ return null; }
			var hashParams	= stringObj.split('/');
			var actParams	= new Hash();
			for(ap=0; ap < hashParams.length; ap++){
				if(hashParams[ap].indexOf(':') > -1){
					paramSet	= hashParams[ap].split(':');
					actParams.set(paramSet[0],paramSet[1]);
				}else{
					actParams.set(hashParams[ap],hashParams[ap]);
				}
			}
			return actParams
		},
		get: function(){ return window.location.hashparams.getHashFromString(location.hash.replace('#',''));},
		set: function(hashParams,replace){
			var hash	= ("#"+ (window.location.hashparams.getStringFromHash(hashParams)));
			if(typeof replace === 'boolean'){
				if(replace === true){
					var href = window.location.href;
					if(href.indexOf('#') > -1){
						href = href.substring(0,href.indexOf('#'));
					};
					window.location.replace(href+hash);
					return true;
				}
			};
			location.hash = hash;
		},
		remove: function(){
			var h	= this.get();
			if(h){
				for(var hi=0; hi < arguments.length ;hi++){
					if(typeof (h.get(arguments[hi])) !== 'undefined'){ h.unset(arguments[hi]); }
				}
			}
			this.set(h,true);
		}
	}
}()
document.observe("dom:ready",function(){
	if(!document.ready){ document.ready = true; document.fire("dom:beforeloaded");}
	if(!document.loaded){ document.loaded = true; document.fire("dom:loaded");}
});
if(typeof nfl=="undefined"){ var nfl={}; }
/**
 * Creates new namespaces under the nfl namespace
 *
 * @param {String}
 *            The name of the new namespace
 */
nfl.namespace=function(){ var a=arguments,o=null,i,j,d;for(i=0;i<a.length;++i){d=a[i].split(".");o=nfl;for(j=(d[0]=="nfl")?1:0;j<d.length;++j){o[d[j]]=o[d[j]]||{};o=o[d[j]];}} return o;};
nfl.namespace("ui","util","global","data","analytics");
nfl.global.debugenabled	= true;
nfl.global.SEARCH_ADS	= true;
/**
 * Writes a message to the console (if available) and prevents programs
 * from throwing errors on browsers missing a console.
 *
 * @param {String}
 *            message The message to write
 */
(function () {
	var f = Prototype.emptyFunction, needsConsole = Object.isUndefined(window.console);

	if (needsConsole && (document.cookies.get('debug') == 'true')) {
		document.include('http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');
	} else if (needsConsole) {
		window.console = { log: f, debug: f, info: f, warn: f, error: f, assert: f, dir: f, dirxml: f, group: f, groupEnd: f, time: f, timeEnd: f, count: f, trace: f, profile: f, profileEnd: f };
		nfl.log = f;
	}
	nfl.log = function(s,r){ try{ console.log.apply(console, arguments); }catch(e){ try{ if(typeof r !== 'undefined'){console.log(s,r);}else{console.log(s);} }catch(e){}; }};
	
}());
nfl.log("loading nfl.js..");
/**
 * Loads in the environmental variables
 */
(function () {
	Object.extend(nfl.global, {
		imagepath    : window.n_imagepath,
		scriptpath	 : window.n_scriptpath,
		flashpath    : window.n_flashpath,
		ENV          : window.n_environment,
		ID_MANAGER   : window.n_id_manager,
		ecmimagepath : window.n_ecmimagepath || '',
		searchdomain : Object.isUndefined(window.n_searchdomain) ? 'search.nfl.com' :
			                    n_searchdomain.indexOf(':') > -1 ? n_searchdomain.substring(0,n_searchdomain.indexOf(':')) :
			                    n_searchdomain,
		SITELIFE_URL : window.n_sitelife || 'http://pluck.nfl.com',
		SITE_URL     : window.n_site || 'http://www.nfl.com'
	});
}())
/**
 * document.domain is required for third-party integration (sitelife) Sets any
 * sub-domain of nfl.com to nfl.com, but does not affect localhost
 */
try {
	document.domain = window.location.hostname.match(/([^\.\/]*\.?[^\.\/]+)$/)[1];
} catch(err) {}
(function () {
	/**
	 * Initialize nfl.util.cookies namespace note: these functions have been moved
	 * to document.cookies. these references are just pointers now. (a.w.)
	 */
	nfl.namespace("util.cookies");
	var cookiePointers = {
		getCookieVal: document.cookies.getValue,
		getExpDate:   document.cookies.getExipiry,
		getCookie:    document.cookies.get,
		setCookie:    document.cookies.set,
		deleteCookie: document.cookies.remove
	};
	Object.extend(nfl.util.cookies, cookiePointers);
	Object.extend(window, cookiePointers);
}());
(function () {
	nfl.namespace('nfl.events');
	Object.extend(nfl.events, {
		/**
		 * Enables Flash to fire prototype custom events.
		 */
		fire: function( _type, _memo, _dispatcher ) {
			Element.fire($(_dispatcher) || document, _type, _memo );
		},
		available: function() { return true; },
		/**
		 * Constant for monitoring the hash change
		 */
		WindowEvent : { HASH_CHANGE: "window:hashchange" }
	});
}());
(function () {
	/**
	 * functions and properties for manipulating ads
	 *
	 * @author arianna.winters
	 * @namespace nfl
	 * @requires nfl
	 */
	nfl.namespace("nfl.ads");
	Object.extend(nfl.ads, {
		collection:       [],
		visibleAds:       0,
		hasRotating:      false,
		rotationInterval: 30,
		internal:         window.n_internal_ads || false
	});
	
	/**
	 * ad object
	 *
	 * @author arianna.winters
	 * @namespace nfl.ads
	 * @class nfl.ads.Ad
	 * @requires nfl.ads
	 */
	nfl.ads.Ad	= Class.create({
		initialize: function(div, params, options) {
			this.pathOnly = (options.pathOnly)?true:false;
			this.params	= params;
			this.options = (typeof options === 'undefined')?{}:options;
			this.tile	= (typeof options.tile === 'undefined')? (nfl.ads.collection.length + 1):options.tile;
			this.rotate	= (typeof options.rotating === 'undefined')? false:options.rotating;
			this.onload	= (options.onload)?' onload="'+options.onload+'"':'';
			this.url	= (typeof this.options.url !== 'undefined')?this.options.url:this.getUrl();
			this.options.write	= (typeof this.options.write === 'undefined')?true:this.options.write;
			this.oid	= div;

			if(!this.pathOnly){
				this.adClassInt	= (nfl.ads.visibleAds + 1);
				var el, count, url;
				if(!div.id){ div, this.tile }
				el			= $(div);
				this.id		= ("ad" + this.adClassInt +'-iframe');
				if(el){
					el.addClassName('ad'+this.adClassInt);
					this.id	= (el.id + '-iframe');
					if(this.options.write){el.innerHTML = this.getIframeHTML();}
				}
				nfl.ads.add(this);
				el = null;
			}else{
				this.adClassInt	= false;
				nfl.ads.add(this);
				return (this.params.replace('#{tile}',this.tile) +';ord=' + adRandom + '?');
			}
		},
		getInternal: function(){
			if(typeof nfl.ads.internal !== 'undefined'){
				for(var adi=0,adl=nfl.ads.internal.length; adi < adl; adi++){
					var matchesAll	= (nfl.ads.internal[adi].length > 0)?true:false;
					for(var adifl=0; adifl < nfl.ads.internal[adi].length; adifl++){
						var match	= nfl.ads.internal[adi][adifl];
						// console.log('getInternal doing a crit match on '+
						// match.id+' '+match.type+' for '+match.match);
						if(match.type == 'global'){
							// console.log(window.location.domain +'!=='+
							// match.match +'?'+(window.location.domain !==
							// match.match));
							if(window.location.domain !== match.match){ matchesAll = false; break; }
						}
						if(match.type == 'url'){
							// console.log(window.location.pathname +'!=='+
							// match.match +'?'+(window.location.pathname !==
							// match.match));
							if(window.location.pathname !== match.match){ matchesAll = false; break; }
						}
						if(match.type == 'section'){
							// console.log(window.location.pathname +'.indexOf('+
							// match.match +') !==
							// 0?'+(window.location.pathname.indexOf(match.match)
							// !== 0));
							if(window.location.pathname.indexOf(match.match) !== 0){ matchesAll = false; break; }
						}
						if(match.type == 'slot'){
							// console.log(this.options.slot +'!=='+ match.match
							// +'?'+(this.options.slot !== match.match));
							if(this.options.slot !== match.match){ matchesAll = false; break; }
						}
					}
					if(matchesAll){
						/* this guy matches the subset criteria, replace him */
						return ('http://www.nfl.com/widgets/ads-served-by-nfl/' + this.options.width + 'x' + + this.options.height + '?template=basic-html-structure&confirm=true');
						// break;
					}
				}
			}
			return false
		},
		getUrl: function(){
			var mInt	= this.getInternal();
			if (mInt) {
				/* do something funny */
				this.url		= mInt;
				this.getInternal	= function(){return mInt};
			}else{
				if(this.tile == 1 && this.options.slot != 'inpage' && this.options.slot != 'videogallery') {
					var path = window.location.pathname;
					/*
					 * if (path != "/" && path != "/home") this.params +=
					 * ";dcopt=ist";
					 */ // the
																							// homepage
																							// 728x90
																							// should
																							// not
																							// have
																							// the
																							// dcopt
																							// value
					this.params += ";dcopt=ist"; /*
													 * applying this to the homepage
													 * because OAO said it should be
													 * site wide. i'll keep the
													 * above line commented out in
													 * case we need it.
													 */
				}
				this.url		= 'http://ad.doubleclick.net/adi/'+ this.params.replace('#{tile}',this.tile) +';ord=' + adRandom + '?';
			}
			return this.url;
		},
		update: function() {
			// nfl.log("reload #"+ this.adClassInt);
			this.url	= this.getUrl(); /* we do this to grab a different ad url */
			this.write();
		},
		write: function(){
			$(this.oid).update(this.getIframeHTML());
			this.setParentSize(); // we do this just in case
		},
		getIframeHTML: function(){
			var retStr		= (this.options.transparent != true)?'<iframe src="'+ this.url +'" id="' + this.id + '" name="' + this.id + '" width="' + this.options.width + '" height="' + this.options.height + '" frameborder="0" scrolling="no"'+ this.onload +'></iframe>':'<iframe src="'+ this.url +'" id="' + this.id + '" name="' + this.id + '" width="' + this.options.width + '" height="' + this.options.height + '" allowTransparency="true" frameborder="0" scrolling="no"'+ this.onload +'></iframe>';
			return retStr
		},
		setParentSize: function(){
			var _p		= $(this.oid);
			var _dims	= {width:parseInt(_p.getStyle('width')),height:parseInt(_p.getStyle('height'))};
			if(this.options.width !== _dims.width && this.options.width > 0){
				_p.setStyle({'width':(this.options.width+'px')});
			}
			if(this.options.height !== _dims.height && _dims.height > 0){
				_p.setStyle({'height':(this.options.height+'px')});
			}
		}
	});
	nfl.ads.rotation	= new (Class.create({
		initialize:function(){
			this.elapsor	= null;
			this.rotator	= null;
			this.interval	= 30; /* we assign a default of 30 just in case */
			this.useElapsed = false;
		},
		rotate: function(){
			// console.info('nfl.ads.rotate');
			var __log	= '';
			nfl.ads.random(); // first update the adRandom var
			nfl.ads.collection.each(function(Ad){if(Ad.rotate){ Ad.update(Ad); __log +='#'+Ad.adClassInt+' "'+ Ad.id+'" rotated.\n'; /* this is a rotating ad, rotate it */ }else{ __log +='#'+Ad.adClassInt+' "'+ Ad.id+'" not rotated.\n'; }});
			console.log('nfl.ads.rotate ('+ this.interval +' secs)\n'+ __log);
			this.elapsed = 0;
			/*
			 * start elapsor when useElapsed changed to true without a rotator
			 * restart
			 */
			if(this.useElapsed && this.elapsor == null){ this.elapsor	= new PeriodicalExecuter(this.countElapsed, 1);}
		},
		start: function(){
			/* make sure this thing is stopped first */
			if(this.rotator !== null){ this.stop(); }
			if(this.useElapsed){
				var __elapsed	= (typeof this.elapsed !== 'undefined')?this.elapsed:0;
				if(__elapsed > 0 && nfl.ads.rotationInterval > __elapsed){
					/* start from last spot */
					var sp	= (nfl.ads.rotationInterval - __elapsed);
					setTimeout(function(){ this.elapsed = 0; this.start(); }.bind(this),sp);
					return;
				}
				/* start elapsed counter */
				this.elapsor	= new PeriodicalExecuter(this.countElapsed.bind(this), 1);
			}
			/* start rotator */
			this.rotator = new PeriodicalExecuter(this.rotate.bind(this), this.interval);
		},
		stop: function(){
			if(this.rotator !== null){this.rotator.stop(); this.rotator = null; }
			if(this.useElapsed && this.elapsor !== null){this.elapsor.stop(); this.elapsor = null;}
			this.elapsed = 0;
		},
		pause: function(){
			/* leave elapsed */
			if(this.rotator !== null){this.rotator.stop(); this.rotator = null; }
			if(this.useElapsed && this.elapsor !== null){this.elapsor.stop(); this.elapsor = null;}
		},
		countElapsed: function(){
			this.elapsed++;
			if(this.elapsed === this.interval){this.elapsed = 0;}
		}
	}))();

	nfl.ads.add	= function(Ad){
		var adIndex	= nfl.ads.collection.length;
		nfl.ads.collection.each(function(Adi,ind){
			if(Adi.id == Ad.id){adIndex = ind; throw $break;}
		}.bind(this));

		if(!Ad.pathOnly){
			if(Ad.rotate == true){
				nfl.log("ad #"+ Ad.adClassInt +" is a rotating ad");
			}else{
				nfl.log("ad #"+ Ad.adClassInt +" is not a rotating ad");
			}
			if(Ad.rotate == true && nfl.ads.hasRotating == false){
				/* has not had any previous rotating ads */
				nfl.ads.hasRotating	= true;
				if(document.loaded){ nfl.ads.rotation.start(); }else{ document.observe("dom:loaded",function(){ nfl.ads.rotation.start(); }); }
			}
			if(adIndex === nfl.ads.collection.length){ nfl.ads.visibleAds++; }
		}
		nfl.ads.collection[adIndex] = Ad;
	}
	nfl.ads.replace = function(Ad){
		var adIndex	= -1;
		nfl.ads.collection.each(function(Adi,ind){
			if(Adi.id == Ad.id){adIndex = ind; throw $break;}
		}.bind(this));
		if(adIndex > -1){
			nfl.ads.collection[adIndex] = Ad;
		}
	}
	nfl.ads.getById = function(id){
		var retAd	= null;
		nfl.ads.collection.each(function(Adi,ind){
			// console.log('nfl.ads.getById: checking '+ Adi.oid +' = '+id);
			if(Adi.oid == id){retAd = Adi; throw $break;}
		}.bind(this));
		return retAd
	}
	/**
	 * Generates new random number for use in creating sets of ads.
	 *
	 * @return {Integer}
	 */
	nfl.ads.random	= function(){ adRandom	= (Math.random() * 1000); return adRandom; };
	nfl.ads.random();
	
}());
(function () {
	nfl.namespace('nfl.util');
	Object.extend(nfl.util, {
		/**
		 * Open a new pop up window.
		 *
		 * @param {string}
		 *            url the url of the window.
		 * @param {string}
		 *            panelName the name of the window.
		 * @param [{object}]
		 *            an object containing key-value pairs of window attributes to
		 *            overide the defaults
		 */
		openPopWindow: function(url, name){
			var win_args = ''; var win_options = {width:800,height:600,toolbar:0,scrollbar:'auto'}
			if(typeof arguments[2] == 'object'){ for(var argName in arguments[2]) { win_options[argName] = arguments[2][argName]; }; for(var argName in win_options) { win_args += (argName+"="+win_options[argName]+","); } win_args = win_args.substring(0,(win_args.length - 1));}
			if(typeof arguments[2] == 'number' && typeof arguments[3] == 'number'){	win_args = 'width='+ arguments[2] +',height='+ arguments[3] +',toolbar=0,scrollbar=auto';}
			if(typeof arguments[2] == 'string'){ win_args = arguments[2];}
			var win	= window.open(url,name,win_args); win.focus();
		},
		/**
		 * Sends a Micro Level call to Omniture to track links. Originally created for
		 * use by the Scorestrip.
		 *
		 * @param {string}
		 *            linkName: the name of the link to track via Omniture.
		 * @param {string}
		 *            propValue: the value of prop35. this can be different form
		 *            linkName.
		 */
		omnitureLinkTracking: function(linkName, propValue){
			var s_analytics = s_gi(s_account);
			s_analytics.linkTrackVars = "prop35";
			s_analytics.prop35 = propValue;
			s_analytics.tl(true,'o',linkName);
		},
		/**
		 * Sends a Page Level call to Omniture to track dynamic page calls on things like tabs etc. 
		 *
		 * @param {string}
		 *            pageName: the name of the page to track via Omniture.
		 * @param {string}
		 *            heirName: the heirarchy path to track via omniture. this is usually the same as 
		 *            pageName with pipe characters instead of colons after the first separator.
		 * @param {string}
		 *            chName: channel value to pass via omniture call.
		 */
		omniturePageTracking: function(pageName, heirName, chName) {
			var s_analytics 	= s_gi(s_account);
			s_analytics.linkTrackEvents = 'event1';
			s_analytics.linkTrackVar	="events,pageName,hier1,prop5,eVar2,eVar3,eVar4";

			s_analytics.pageName	= pageName;
			s_analytics.hier1 		= heirName;
			s_analytics.channel		= chName;
			s_analytics.prop5 		= heirName;
			s_analytics.eVar2		= pageName;
			s_analytics.eVar3		= chName;
			s_analytics.eVar4 		= heirName;
			s_analytics.prop35		= '';
			s_analytics.prop6		= '';

			s_analytics.events		= 'event1';
			s_analytics.t();
		}
	});
	window.$openWindow = nfl.util.openPopWindow; // shorthand pointer
}());
(function () {
	/**
	 * Image Preloading functions.
	 */
	var pointers = {
		notFoundImg: null,
		checks:      {
			generic: function(image){
				image.src = notFoundImg.src;
			}
		},
		loadImages: function(){
			var imagesToPreload = arguments, preloadedImages = [], i, l;
			for (i = 0, l = imagesToPreload.length; i < l; i++) {
				preloadedImages[i]     = document.createElement('img');
				preloadedImages[i].src = imagesToPreload[i];
			}
			return preloadedImages;
		},
		loadImages2: function(imagesToPreload) {
			var preloadedImages = [], i, l;
			for (i = 0, l = imagesToPreload.length; i < l; i++) {
				preloadedImages[i] = new Image();
				preloadedImages[i].src = imagesToPreload[i];
			}
			return preloadedImages;
		},
		loadImages3: function(imagesToPreload) {
			var preloadedImages = [], i, l, c;
			for (i = 0, l = imagesToPreload.length; i < l; i++) {
				c = i + 1;
				$('sr_image' + c).src = imagesToPreload[i];
			}
			return preloadedImages;
		}
	};
	nfl.namespace("nfl.util.images.preloader");
	Object.extend(nfl.util.images.preloader, pointers);
	Object.extend(window, {
		preloadImages:  pointers.loadImages,
		preloadImages2: pointers.loadImages2,
		preloadImages3: pointers.loadImages3
	});
}());
/**
 * Methods for creating and updating the scorestrip
 *
 * @author ryan.cannon
 * @namespace nfl.global
 * @class Scorestrip
 * @requires swfobject, nfl
 */
nfl.global.Scorestrip = Class.create({
	/**
	 * Adds the scorestrip to the page
	 *
	 * @param {String}
	 *            weekColor Hex numer for the text color of the current week
	 *            defaults to "FFFFFF
	 * @param {String}
	 *            scheduleColor Hex numer for the text color of the schedules
	 *            link
	 * @param {String}
	 *            ssID ID of the element to write the scoretrip to, defaults to
	 *            'fo_scorestrip'
	 * @param {Hash}
	 *            options Overwrites any default options.
	 * @returns {String} The ID of the element to which the scorestrip was
	 *          written.
	 */
	initialize: function(divID, options) {
		this.ssID 	= 'fo_scorestrip';
		this.opts	= options;
	 	this.write();
	},
	write: function(){
		/* merge in baseURL into flash vars */
		this.opts.flashVars	= (this.opts.flashVars !== null)?this.opts.flashVars:{};
		/* USE THIS RegExp instead
			/(?:local|(?:(?:origin\-(?:dev|test|stage|prod)\.www)|(?:(?:dev|test|stage|prod)(?:app|web)\d+\.la3)))\.nfl\.com$/
		*/
		var validSubDomains	= [
			                 	  'local.nfl.com',
			                 	  'dev.www.nfl.com',
			                 	  'test.www.nfl.com',
			                 	  'stage.www.nfl.com',
			                 	  'origin-dev.www.nfl.com',
			                 	  'origin-test.www.nfl.com',
			                 	  'origin-stage.www.nfl.com',
			                 	  'origin-prod.www.nfl.com',
			                 	  'testweb01.la3.nfl.com',
			                 	  'testapp01.la3.nfl.com',
			                 	  'stageweb01.la3.nfl.com',
			                 	  'stageweb02.la3.nfl.com',
			                 	  'stageweb03.la3.nfl.com',
			                 	  'stageweb04.la3.nfl.com',
			                 	  'stageapp01.la3.nfl.com',
			                 	  'stageapp02.la3.nfl.com',
			                 	  'stageapp03.la3.nfl.com',
			                 	  'stageapp04.la3.nfl.com',
			                 	  'stageapp05.la3.nfl.com',
			                 	  'stageapp06.la3.nfl.com',
			                 	  'stageapp07.la3.nfl.com',
			                 	  'prodweb01.la3.nfl.com',
			                 	  'prodweb02.la3.nfl.com',
			                 	  'prodweb03.la3.nfl.com',
			                 	  'prodweb04.la3.nfl.com',
			                 	  'prodweb05.la3.nfl.com',
			                 	  'prodweb06.la3.nfl.com',
			                 	  'prodweb07.la3.nfl.com',
			                 	  'prodweb08.la3.nfl.com',
			                 	  'prodapp01.la3.nfl.com',
			                 	  'prodapp02.la3.nfl.com',
			                 	  'prodapp03.la3.nfl.com',
			                 	  'prodapp04.la3.nfl.com',
			                 	  'prodapp05.la3.nfl.com',
			                 	  'prodapp06.la3.nfl.com',
			                 	  'prodapp07.la3.nfl.com',
			                 	  'prodapp08.la3.nfl.com',
			                 	  'prodapp09.la3.nfl.com',
			                 	  'prodapp10.la3.nfl.com',
			                 	  'prodapp11.la3.nfl.com',
			                 	  'prodapp12.la3.nfl.com',
			                 	  'prodapp13.la3.nfl.com',
			                 	  'prodapp14.la3.nfl.com'
			                 	  ];
		this.opts.flashVars['baseURL'] = (window.location.host.match(/(?:[^\/]+)\.nfl\.com/) && validSubDomains.indexOf(window.location.hostname) == -1) ? window.location.protocol + '//www.nfl.com' : window.location.protocol + '//' + window.location.host;

	 	var o = $H({
	 		id: this.ssID,
			flashVars: this.opts.flashVars,
			params: { wmode: "transparent" },
			width: '870',
			height: '115',
			version: "8",
			background: "#FFFFFF"
		});
		this.flash = new nfl.media.Flash(nfl.global.imagepath + '/flash/scorestrip.swf', "header-scorestrip", o.merge($H(this.opts)));
		/* checked against prototype 1.6.0.2 */
	},
	getID: function() { return this.ssID },
	getFlash: function() { return this.flash },
	reload: function() {
		$("header-scorestrip").update();
		this.write();
	}
});
/**
 * Provides constants for observing and firing authentication events
 * Authentication events should be fired with a "component"
 *
 * @namespace nfl.events
 * @class AuthenticationEvent
 */
nfl.events.AuthenticationEvent = function () {
	var AE, prefix;
	prefix = 'nfl:authentication:';
	AE = { SIGN_IN: prefix + 'signin', SIGN_OUT: prefix + 'signout', AUTH_FAILURE: prefix + 'authfailure' };
	// monitor events
	if (window.console) {
		function logger(event) { console.log('AuthenticationEvent: ' + event.eventName, event.memo); }
		for (var i in AE) { document.observe(AE[i], logger);}
	}
	return AE;
}();
/**
 * The Authentication class provides static methods to get/set/clear cookies
 * associated with a user. Fires an AuthenticationEvent when either set or clear
 * is called. e.g.:
 *
 * document.observe(nfl.events.AuthenticationEvent.SIGN_IN, doSomething);
 *
 * In order to be logged in, you must have all three NFL cookie: userId, at &
 * ptnr.
 *
 * @namespace nfl.global
 * @class Authentication
 */
nfl.global.Authentication = function () {
	var AuthenticationEvent = nfl.events.AuthenticationEvent,
	    Cookies			= { USER: 'userId', SITELIFE: 'at', PARTNER: 'ptnr' },
	    COMPONENT		= 'AuthenticationEvent',
	    DOMAIN			= document.domain,
	    PATH			= '/',
	    COOKIE_SIGN_IN	= 'CookieSignIn',
	    SIGN_IN_APP     = '/fans/login',
	    nflCookie       = document.cookies.get(Cookies.USER).toQueryParams(),
	    pluckCookie     = document.cookies.get(Cookies.SITELIFE).toQueryParams(),
	    partnerCookie   = document.cookies.get(Cookies.PARTNER).toQueryParams(),
	    team, username;

	if (nflCookie.u) {
		team			= decodeURIComponent(nflCookie.t);
		username		= decodeURIComponent(nflCookie.u);
	}
	// if these values don't match, don't consider us logged out
	if ( ! ( isUser(partnerCookie) && isUser(pluckCookie) ) ) {
		onSignOut();
	}

	document.observe('dom:loaded', initialize);
	document.observe(AuthenticationEvent.SIGN_OUT, onSignOut);
	document.observe(AuthenticationEvent.SIGN_IN, onSignIn);

	// Listens for dom:loaded event
	function initialize (e) {
		if (is_authenticated()) {
			// If we're referred from login, fire log the event
			if (document.referrer.indexOf(nfl.global.ID_MANAGER + SIGN_IN_APP) === 0) {
				s_analytics.events = "event11";
			}
			document.fire(AuthenticationEvent.SIGN_IN, { component: COOKIE_SIGN_IN, username: username, team: team });
		}
	}

	// Returns bool if the cookie's user matches the supplied value
	function isUser(_cookie) {
		return _cookie && _cookie.u && decodeURIComponent(partnerCookie.u) === username;
	}

	// Returns bool if user is authenticated or not
	function is_authenticated() {
		return !! username;
	}

	// Listener for a SIGN_OUT event
	function onSignOut(e) {
		username = team = null;
		/* delete cookies for site */
		document.cookies.remove(Cookies.USER, PATH, DOMAIN);
		document.cookies.remove(Cookies.SITELIFE, PATH, DOMAIN);
		document.cookies.remove(Cookies.PARTNER, PATH, DOMAIN);
	}

	function onSignIn(e) {
		if ( e.memo.component === COOKIE_SIGN_IN ) { return; }
		username = e.memo.username;
		team     = e.memo.team;
	}

	return {
		signOut: function() { document.fire(AuthenticationEvent.SIGN_OUT, { component: COMPONENT });},
		isAuthenticated: function() { return is_authenticated();},
		getUser: function() { return is_authenticated() ? { username: username, team: team } : null; }
	};
}();
/**
 * The Header class observes AuthenticationEvents and updates the login/logout
 * buttons that appear in most site headers.
 *
 * @namespace nfl.global
 * @class Header
 * @requires nfl.global.Authentication
 */
nfl.global.Header = function(){
	var AuthenticationEvent = nfl.events.AuthenticationEvent,
	    ID = {
			LIST:		'hd-micro-nav-list',
			RAIL:		'top-rail',
			SIGN_IN:	'link-user-sign-in',
			SIGN_OUT:	'link-user-sign-out',
			REGISTER:	'link-user-register',
			PROFILE:	'link-user-profile'
		},
		initialized = false,
		profileTemplate;

	document.observe(AuthenticationEvent.SIGN_IN, onSignIn);
	document.observe(AuthenticationEvent.SIGN_OUT, onSignOut);
	document.observe('dom:loaded', initialize);

	function initialize() {
		if (! $(ID.LIST) && !$(ID.RAIL) ) { return killHeaderLinks();}

		// Hide the sign out info if it hasn't yet been addressed
		if (! initialized) { onSignOut(); }
		initialized = true;
	}
	function onSignIn(e) {
		try {
			var profile = $(ID.PROFILE);

			if (! profileTemplate) {
				profileTemplate = profile.templatize();
			}

			profile.update(profileTemplate.evaluate(e.memo));

			initialized = true;

			$(ID.SIGN_IN, ID.REGISTER).invoke('hide');
			$(ID.SIGN_OUT, profile).invoke('show');
		}
		catch(e) { killHeaderLinks(e);}
	}

	function onSignOut() {
		try {
			var profile = $(ID.PROFILE);

			profile.update("");

			$(ID.SIGN_IN, ID.REGISTER).invoke('show');
			$(ID.SIGN_OUT, profile).invoke('hide');
		}
		catch(e) { killHeaderLinks(e); }
	}
	function killHeaderLinks(e) {
		nfl.log("nfl.global.Header killHeaderLinks()");
		nfl.log(e);
		document.stopObserving(AuthenticationEvent.SIGN_IN, onSignIn);
		document.stopObserving(AuthenticationEvent.SIGN_OUT, onSignOut);
	}
	function replace_return(path) {
		return function (el) {
			el.href = el.href.replace(/returnTo=([^#&]*)/, 'returnTo=' + encodeURIComponent(path));
		}
	}
	return {
		setReturnToURLs: function(path) {
			$$('#' + ID.LIST + ' li a').each(replace_return(path));
		}
	}
}();
/**
 * Adds decorating <div> elements
 *
 * @namespace nfl.global
 * @class Decorators
 */
nfl.global.Decorators = function() {
	// initialize at page load
	document.observe('dom:loaded',initialize);

	function initialize() {
		var el = $('copyright');
		if (! el) { return;}
		nfl.global.Decorators.add(el, ['bl', 'br'], false);
		var els = $$('div.shadowed').each(nfl.global.Decorators.add);
	}
	return {
		/**
		 * Adds empty divs to an element in order to add decoration
		 *
		 * @method add
		 * @param {String |
		 *            HTMLElement} el the element to add decoration
		 * @param {Array}
		 *            classNamesArray array of classNames for the decorating
		 *            divs. default: ['b', 'r', 'tr', 'br', 'bl']
		 * @param {boolean}
		 *            wrap whether the element should be wrapped in a container
		 */
		add: function(el, classNamesArray, wrap) {
			var c, d, e, h, w;
			w = (typeof wrap == 'undefined') ? true : wrap;
			c = classNamesArray || ['b', 'r', 'tr', 'br', 'bl'];
			h = '<div class="' + c.join('"></div><div class="') + '"></div>';
			e = $(el);
			if (w) {
				d = document.createElement('div');
				d.className = "has-shadow";
				d.innerHTML = h;
				if (e.id) { d.id = e.id + "-wrap" }
				e.parentNode.insertBefore(d, e);
				d.insertBefore(e, d.firstChild);
			}
			else {
				e.innerHTML += h;
				e.addClassName('has-shadow');
			}
			return true;
		}
	}
}();
/**
 * The Footer class inserts a Flash footer with dynamic text and text color into
 * the document.
 *
 * @namespace nfl.global
 * @class Footer
 */
nfl.global.Footer = Class.create();
nfl.global.Footer.prototype = {
	initialize: function(id) {
		this.textColor = "#FFFFFF";
		this.id = id;
	},
	setTextColor: function(c) {
		this.textColor = c;
		return this;
	},
	write: function() {
		var so, el, text;
		el = $(this.id);
		text = (el.innerText || el.textContent).strip().toUpperCase();
		new nfl.media.Flash(nfl.global.imagepath + "/flash/footer.swf", el, $H({
			width: "705",
			height: "25",
			version: "8",
			background: "#000000",
			params: $H({ wmode: "transparent"}),
			flashVars: $H({
				debug: true,
				allowFullScreen: false,
				footerText: text,
				textColor: this.textColor
			})
		}));
		el = null;
	}
};
/**
 * The CenterPiece module inserts a Flash centerpiece of various sizes into the
 * document.
 *
 * @namespace nfl.global
 * @class CenterPiece
 */
nfl.global.CenterPiece = Class.create({
	/**
	 * Constructor for the CenterPiece class.
	 *
	 * @constructor
	 * @param {String}
	 *            type The type of CenterPiece. Accepted vaults are "normal",
	 *            "wide" and "extra-wide". the window object. The listener can
	 *            override this.
	 * @param {String}
	 *            flashURL path to the Flash file for the centerpiece.
	 * @param {String}
	 *            subjectType The subjecType of the page calling the Centerpiece
	 *            (normal only).
	 * @param {String}
	 *            modifiedDate The date the centerpiece content was modified
	 *            (normal only).
	 * @param {Object}
	 *            options An associated array used to override any defaults in
	 *            the CenterPiece.
	 */
	initialize: function(divID, type, flashURL, subjectType, modifiedDate, options) {
		var width, so, div, anchor;
		div = $(divID);
		div.addClassName("cp-" + this.type);
		var o = $H({
			width: ((type == "extra_wide") ? "965" : (type == "wide") ? "660" : "408"),
			height: "325",
			version: "8.0",
			background: "#FFFFFF",
			params: { wmode: (this.type == "normal") ? 'opaque' : 'transparent' },
			flashVars: $H({ IMAGEPATH: nfl.global.imagepath }),
			playerVolume: 50,
			pauseSeconds: 10
		});
		if (type == "normal") {
			var tmpO	= o.get('flashVars');
			tmpO.set("playerXmlUrl","/widget/centerpiece?subjectType=" + encodeURIComponent(subjectType));
			tmpO.set('modifiedDate',modifiedDate);
			tmpO.set("playerVolume",o.get('playerVolume'));
			tmpO.set("pauseSeconds",o.get('pauseSeconds'));
			o.set('flashVars',tmpO);
		}
		this.flash = new nfl.media.Flash(flashURL, div, o.merge($H(options || {})));
	},
	getFlash: function() { return this.flash }
});
nfl.namespace("nfl.media");
nfl.media.Flash = Class.create({
	initialize: function(url, el, options) {
		var so, id, o, fID;
		// nfl.log("nfl.media.Flash.initialize: 1");
		id = (typeof el == 'string') ? el : el.id;
		fID = id.replace(/-/g, "") + "Flash";
		o = $H({ id: fID, width: "550", height: "400", version: "8", background: "#FFFFFF" }).merge($H(options)); /*
																													 * checked
																													 * against
																													 * prototype
																													 * 1.6.0.2
																													 */
		// nfl.log("nfl.media.Flash.initialize: 2");
		this.fid = o.get('id');
		if ($(this.fid)) { throw("Cannot embed Flash movie: Element with the id \"" + this.fid + "\" already exists."); }
		var optParams	= new Hash();
		var optVars		= new Hash();
		// nfl.log("nfl.media.Flash.initialize: 3");
		// nfl.log("typeof options = "+ (typeof options));
		if((typeof options == 'object') && options.get){
			if(typeof options.get('params') == 'object'){
				optParams	= $H(options.get('params'));
				optVars		= $H(options.get('flashVars'));
			}else{
				try{
					optParams = $H(options['params'])
				}catch(e){}
			}
		}
		// nfl.log("nfl.media.Flash.initialize: 4");
		o.set('params',$H({ allowScriptAccess: "always", wmode: "opaque" }).merge(optParams)); /*
																								 * checked
																								 * against
																								 * prototype
																								 * 1.6.0.2
																								 */
		o.set('flashVars', optVars);
		so = new SWFObject(url, this.fid, o.get('width') + "", o.get('height') + "", o.get('version') + "", o.get('background'));
		o.get('params').each(function(pair) { so.addParam(pair.key, pair.value) });
		o.get('flashVars').each(function(pair) { so.addVariable(pair.key, encodeURIComponent(pair.value)) });
		// nfl.log("nfl.media.Flash.initialize: 5");
		so.write(id);
		so = null;
		// nfl.log("nfl.media.Flash.initialize: 6");
	},
	getMovie : function(){
		return (navigator.appName.indexOf("Microsoft") != -1)?
			function() { return window[this.fid] } :
			function() { return document[this.fid] }
	}(),
	exec: function(s) { this.getMovie()[s]();}
});

/**
 * Audio Panel/Window
 */
nfl.namespace('nfl.media.audio');
nfl.media.audio.player = function(contentId){
	nfl.util.openPopWindow("/audioplayer?id=" + contentId, 'audioPlayer', {width:760,height:410,toolbar:0,scrollbar:'auto'});
};

/* event logging */
(function () {
	function logEvent(event) {
		nfl.log('{' + event.eventName + '}');
	}
	
	document.
		observe('dom:loaded', logEvent).
		observe('dom:beforeloaded', logEvent).
		observe('dom:ready', logEvent).
		observe('window:hashchange', logEvent);
}());
(function () {
	/**
	 * Assorted IE6 patches and hacks
	 */
	(function IE6BackgroundImageFix(){
		if (Prototype.Browser.IE && navigator.appVersion.indexOf('MSIE 6.0')!=-1) {
			try { document.execCommand("BackgroundImageCache", false, true); }
			catch(err) { return false; }
			return true;
		}
		else return false;
	})();
	(function IEDoesNotSupportABBRUntilThis() {
		document.createElement('abbr');
	})();
	nfl.namespace("nfl.bandages");
	nfl.bandages.IE6HeaderFixes = Class.create({
		initialize: function (options) {
			if ( navigator.appVersion.indexOf('MSIE 6.0') === -1 &&  document.compatMode !== 'BackCompat' ) { return; }
			try{
				/* <iframe id="DivShim" scrolling="no" frameborder="0"></iframe> */
				var iframe = document.createElement('iframe');
				iframe.id = "DivShim";
				iframe.setAttribute("scrolling","no");
				iframe.setAttribute("frameborder","0");
				nfl.bandages.IE6NavigationId = (typeof options['navId'] == 'undefined')?'nav':options['navId'];
				var nav = document.getElementById(nfl.bandages.IE6NavigationId);
				nav.parentNode.insertBefore(iframe, nav);
				var sfEls = nav.getElementsByTagName("LI");
				for (var i=0; i<sfEls.length; i++) {
					sfEls[i].onmouseover=onRollOver;
					sfEls[i].onmouseout=onRollOut;
				}
			} catch(err){}
			Event.observe(window, 'unload', cleanup);
			iframe = nav = sfEls = null;
			function cleanup(e) {
				var sfEls = document.getElementById(nfl.bandages.IE6NavigationId).getElementsByTagName("LI");
				for (var i=0; i<sfEls.length; i++) {
					sfEls[i].onmouseover = null;
					sfEls[i].onmouseout = null;
				}
				sfELs = null;
			}
			function ie6CoverDropDowns(menuButton, newState) {
				if(newState == 'mouseover') {
				   var DivRef = menuButton.getElementsByTagName("UL")[0];
				   var IfrRef = document.getElementById('DivShim');
				    DivRef.style.display = "block";
				    IfrRef.style.top = DivRef.offsetTop;
				    IfrRef.style.left = DivRef.offsetLeft;
				    IfrRef.style.width = DivRef.offsetWidth;
				    IfrRef.style.height = DivRef.offsetHeight;
				    IfrRef.style.zIndex = DivRef.style.zIndex + 1;
				    IfrRef.style.display = "block";
					if ( menuButton.getElementsByTagName("UL").length > 1 ) // for
																			// the
																			// teams
																			// drop
																			// down
																			// which
																			// is
																			// two
																			// ULs
					{
					   var DivRef2 = menuButton.getElementsByTagName("UL")[1];
					    DivRef2.style.display = "block";
					    // the second UL for teams overflaps the first one, so the
						// -16 removes
						// a not so pretty white line next to the that dropdown in
						// ie6
						// @todo: use Prototype Regions
					    IfrRef.style.width = ((DivRef.offsetWidth + DivRef2.offsetWidth) - 16) + 'px';
					}

				} else {
				   var DivRef = menuButton.getElementsByTagName("UL")[0];
				   var IfrRef = document.getElementById('DivShim');
				    DivRef.style.display = "none";
				    IfrRef.style.display = "none";
					if ( menuButton.getElementsByTagName("UL").length > 1 ) // for
																			// the
																			// teams
																			// drop
																			// down
																			// which
																			// is
																			// two
																			// ULs
					{
					   var DivRef2 = menuButton.getElementsByTagName("UL")[1];
					    DivRef2.style.display = "none";
					}
				}
			}
			function onRollOver(e) {
				if(!($(this).hasClassName("sfhover"))){ $(this).addClassName("sfhover"); }
				if((this.parentNode.id==nfl.bandages.IE6NavigationId) && (this.getElementsByTagName("UL").length != 0) ){ ie6CoverDropDowns(this, 'mouseover'); }
			}
			function onRollOut(e){
				if($(this).hasClassName("sfhover")){ $(this).removeClassName("sfhover"); }
				if((this.parentNode.id==nfl.bandages.IE6NavigationId) && (this.getElementsByTagName("UL").length != 0) ){ ie6CoverDropDowns(this, 'mouseout'); }
			}
		}
	});
	nfl.bandages.IE6FooterFixes = function(){
		if (Prototype.Browser.IE && (navigator.appVersion.indexOf('MSIE 6.0')!==-1 || document.compatMode === 'BackCompat')) {
			function getAlphaImageLoader(path) {
				return "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + nfl.global.imagepath + path + "')";
			}
			try {
				$('ft-teams-afc-mark').style.filter = getAlphaImageLoader('/img/global/ft-teams-marks-ie6-afc.png');
				$('ft-teams-nfc-mark').style.filter = getAlphaImageLoader('/img/global/ft-teams-marks-ie6-nfc.png');
				$('ft-teams-afc-mark-container').select('div.ft-teams-parenthesis').first().style.filter = getAlphaImageLoader('/img/global/ft-teams-marks-ie6-brace.png');
				$('ft-teams-nfc-mark-container').select('div.ft-teams-parenthesis').first().style.filter = getAlphaImageLoader('/img/global/ft-teams-marks-ie6-brace.png');
			}
			catch(err) {}
		}
	};
}());

nfl.namespace('widgets');
nfl.events.VideoPlayerEvent = {
	INITIALIZED:       'videoplayer:initialized',
	AVAILABLE:         'videoplayer:readyToLoad',
	READY_TO_PLAY:     'videoplayer:waitingToPlay',
	UNAVAILABLE:       'videoplayer:unavailable',
	AD_START:          'videoplayer:adPlaying',
	AD_COMPLETE:       'videoplayer:adComplete',
	AD_LOADED:         'videoplayer:adLoaded',
	PRE_ROLL_START:    'mediaplayer:preRollStart',
	PRE_ROLL_COMPLETE: 'mediaplayer:preRollComplete',
	PLAY:              'videoplayer:play',
	PAUSE:             'videoplayer:pause',
	POST_ROLL_START:   'mediaplayer:postRollStart',
	PLAYBACK_COMPLETE: 'flash:complete',
	RESTART:           'videoplayer:restart',
	ADD_TO_FAVORITES:  'mediaplayer:addToFavorites',
	PLAYING_IN_HQ:     'videoplayer:playingInHQ',
	PLAYING_IN_SQ:     'videoplayer:playingInSQ',
	JSON_LOADED:       'videoplayer:json:loaded',
	LBALXML_LOADED:    'videoplayer:loadbalancerxml:loaded',
	HTML5DATALOADED:   'videoplayer:htmlfivedata:loaded'
};
/**
 * The VideoPlayer class allows embedding of the NFL video player.
 *
 * @namespace nfl.widgets
 * @class VideoPlayer
 */
nfl.widgets.VideoPlayer = (function(){

	var OPTIONAL_ARGUMENTS   = $w('contentId companionSize related playerName adSetting adRatio dartURL autoplay channelId'),
	    ALT_CONTENT_TEMPLATE = new Template(
	        '<div id="#{id}" style="visibility:hidden">' +
	                '<a href="http://get.adobe.com/flashplayer/" target="_blank">' +
	                        '<img style="width:#{w}px;height:#{h}px" src="' +
	                        nfl.global.imagepath +
	                        '/img/video/flash-required-#{origW}x#{origH}.png" alt="Flash is required to watch videos on NFL.com. Please click here to install Flash on your computer." />' +
	                '</a>' +
	        '</div>'
	    ),
	    AKAMAI_ATTRIBUTION   = '<span class="attribution replaced">HQ video delivered by Akamai <span></span></span>',
	    MINIMUM_VERSION		 = 10,
	    VideoPlayerEvent     = nfl.events.VideoPlayerEvent,
	    VideoPlayer          = null,
	    HTML5VideoPlayer     = null,
	    FLASH_VERSION        = Object.isUndefined(window.deconcept)? {'major':0,'minor':0,'rev':0} : deconcept.SWFObjectUtil.getPlayerVersion();  FLASH_VERSION.major = (window.location.hash !== '' && (window.location.hash).indexOf('fmt=HTML5') > -1)? 0 : FLASH_VERSION.major;

	function getSizeOptions( size ) {
		switch( size ) {
			case 'large':    return { w: '615', h: '346', f: 'inline-video-player' };
			case 'off-site': return { w: '384', h: '216', f: 'player'};
			case 'detail':   return { w: '768', h: '432', f: 'video-detail-player' };
			default:         return { w: '384', h: '216', f: 'inline-video-player' };
		}
	}
	
	function cleanUpEffect(_effect) {
		delete _effect.element.effect;
	}

	function hideAkamaiAttribution(_e) {
		var el = _e.element(), attribution = el.previous();

		if (attribution.effect) {
			attribution.effect.cancel();
		}
		if(typeof Effect === 'undefined'){
			attribution.setStyle({'bottom':'0px'});
		}
		attribution.effect = new Effect.Morph(attribution, {
			afterFinish: cleanUpEffect,
			style: { bottom: '0px' }
		});
	}

	function showAkamaiAttribution(_e) {
		var el = _e.element(), attribution = el.previous();

		if (attribution.effect) {
			attribution.effect.cancel();
		}
		if(typeof Effect === 'undefined'){
			// effect is undefined, do it old school. scriptaculous probably not included.
			attribution.setStyle({'bottom':(0 - attribution.offsetHeight + 'px')});
			return true
		}
		attribution.effect = new Effect.Morph(attribution, {
			afterFinish: cleanUpEffect,
			style: { bottom: 0 - attribution.offsetHeight + 'px' }
		});
	}

	function proxyOnDocument(_e) {
		document.fire(_e, _e.memo);
	}

	function addProxyListener(_pair) {
		this.observe(_pair.value, proxyOnDocument);
	}

	function removeProxyListener(_pair) {
		this.stopObserving(_pair.value, proxyOnDocument);
	}
	
	VideoPlayer = Class.create({
		initialize: function( config ) {
			this.config = config;
			console.info('initializing video player..');
			
			this.write();
			if(FLASH_VERSION.major === 0){
				this.loadHTML5VideoForNonFlash();
			}
		},
		loadHTML5VideoForNonFlash: function(){
			// set up transports
			this.config.transplants	= {
					'AKAMAI_ATTRIBUTION':AKAMAI_ATTRIBUTION,
					'ALT_CONTENT_TEMPLATE':ALT_CONTENT_TEMPLATE,
					'showAkamaiAttribution':showAkamaiAttribution,
					'hideAkamaiAttribution':hideAkamaiAttribution,
					'getSizeOptions':getSizeOptions
			};
			                      	   
			// load html 5 video player 
			if(!$('imported-js-nfl-widgets-html5video')){
				// wait for loaded event 
				document.observe('lib:loaded:html5video', function(){ HTML5VideoPlayer = new nfl.widgets.HTML5VideoPlayer(this.config); }.bind(this));
				document.include('/scripts/lib/nfl.widgets.html5video.js');
			}else{
				HTML5VideoPlayer = new nfl.widgets.HTML5VideoPlayer(this.config);
			}		
		},
		write: function(){
			var sizeOptions, so, id, divid, swfid, container, div;
			
			id = this.config.uniqid || 'nflvideo-' + this.config.contentId;
			if ( /^\d/.test(id) ) {
				id = 'v' + id;
			}

			divid = id + '-video';
			this.swfid = swfid = id.replace(/-/g, '') + 'swf';
			this.geometry	= getSizeOptions( this.config.size );
			this.geometry.origW = this.geometry.w;
			this.geometry.origH = this.geometry.h;
			if ( this.config.width ) {
				this.geometry.w = this.config.width;
			}
			if ( this.config.height ) {
				this.geometry.h = this.config.height;
			}
			Element.setStyle(this.config.uniqid, { width: this.geometry.w + 'px', height: this.geometry.h + 'px' });
			var o = this.geometry;
			o.id = divid;
			o.bgcolor = (typeof this.config.bgcolor !== 'undefined')?this.config.bgcolor:'#000000';
			so    = new SWFObject(
				nfl.global.flashpath + "/flash/video/" + o.f + ".swf",
				this.swfid, this.geometry.w, this.geometry.h, ""+MINIMUM_VERSION+"", o.bgcolor, true
			);
			
			so.useExpressInstall(nfl.global.flashpath + "/flash/expressinstall.swf");
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowFullScreen', 'true');
			so.addParam('wmode', (typeof this.config.wMode !== 'undefined')?this.config.wMode:'opaque');
			so.addVariable('uniqid', this.swfid);
			OPTIONAL_ARGUMENTS.each(function(arg) {
				if (this.config[arg]) { so.addVariable(arg, this.config[arg]); }
			}.bind(this));

			this.so = so;
			if ( this.config.containerId && (container = $( this.config.containerId )) ) {
				divid = container.identify();
			}
			else if ( this.config.write === false ) {
                return;
			}
            else {
            	document.write( ALT_CONTENT_TEMPLATE.evaluate( o ) );
            }

            setTimeout(function() {
            	var div = $(divid), swf;
            	so.write(divid);

            	div.
            		insert({ top: AKAMAI_ATTRIBUTION }).
            		setStyle({ visibility: "visible" });
				
            	$(swfid).
					observe(VideoPlayerEvent.PLAYING_IN_HQ, showAkamaiAttribution).
					observe(VideoPlayerEvent.PLAYING_IN_SQ, hideAkamaiAttribution)
					/*. TODO: scope these events!
					observe(VideoPlayerEvent.UNAVAILABLE, hideAkamaiAttribution).
					observe(VideoPlayerEvent.PLAYBACK_COMPLETE, hideAkamaiAttribution).
					observe(VideoPlayerEvent.AVAILABLE, hideAkamaiAttribution)*/;
            }, 50);
		},
		instance: function() {
			return $( this.swfid );
		},
		proxyEvents: function() {
			$H(nfl.events.VideoPlayerEvent).each(addProxyListener, this.instance());
		},
		stopProxyingEvents: function() {
			$H(nfl.events.VideoPlayerEvent).each(removeProxyListener, this.instance());
		}
	});

	VideoPlayer.isNetSessionInstalled = function() {
		if (Object.isUndefined(window.DLMHelper)) {
			throw new Error('nfl.widgets.VideoPlayer.isNetSessionInstalled() called without including dlm.js');
		}
		return window.DLMHelper.installed;
	};
	VideoPlayer.installNetSession = function(_e) {
		// Cancel the event, if any.
		if (_e && _e.stop) { _e.stop(); }

		var popup = window.open(
			nfl.global.SITE_URL + '/widgets/videos/downloader?template=basic-html&confirm=true',
			'installer',
			'width=465,height=364,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no'
		);
		popup.focus();
	};
	return VideoPlayer;
}());
nfl.widgets.VideoPlayers = {};

/*
 * @author arianna.winters @class nfl.widgets.Carousel @param {String} |
 * {Object} parent container element of ul element
 */
nfl.widgets.Carousel = Class.create({
	initialize: function(container,options){
		this.container	= $(container);
		console.log('initializing '+container);
		this.list		= this.container.select('.list-items').first();
		this.options	= (typeof options !== 'undefined')?options:{debug:false};
		this.rows		= (typeof this.options.rows !== 'undefined')? this.options.rows:1;
		this.evtprefix	= (typeof this.options.evtprefix !== 'undefined')?this.options.evtprefix:'nfl';
		this.totalPages	= -1;
		this.portwidth	= 0;
		this.totalWidth = 0;
		this.relativePaging = false;
		this.options.itempadding = (typeof this.options.itempadding !== 'undefined')? this.options.itempadding:-1;
		this.options.debug = (typeof this.options.debug !== 'undefined')?this.options.debug:false;
		this.options.slide = (typeof this.options.slide !== 'undefined')?this.options.slide:true;

		this.console	= (this.options.debug == true)?console:{log:function(){},info:function(){},warn:function(){}}

		this.boundHandlers	= {};
		this.boundHandlers.onScroll = this.onScroll.bindAsEventListener(this);
		this.boundHandlers.onPageChange = this.onPageChange.bindAsEventListener(this);

		/* set list width to children total width */
		var tChildSel	= (this.list.select('.list-page').length > 0)?'.list-page':'li';
		// this.console.log('child selector: '+tChildSel+', there are
		// '+this.list.select(tChildSel).length+' of these elements');
		var tChildren	= this.list.select(tChildSel);
		tChildren.each(function(ele){
			this.totalWidth = this.totalWidth+(this.getItemTotalWidth(ele));
		}.bind(this));
		if(this.rows > 1){
			this.totalWidth	= (this.getItemTotalWidth(this.list.select('li').first()) * (Math.ceil(this.list.select('li').length / this.rows)));
		}

		this.list.setStyle({width:(this.totalWidth)+'px'});
		this.console.log('set list style to '+this.list.getStyle('width'));
		this.scrollMultiplyer = 1;
		this.originalLeftMargin	= (parseInt(this.list.getStyle('margin-left').replace('px','')));
		// console.log('initializing '+container+' ending.');
		document.observe(this.evtprefix+':carousel:scroll',this.boundHandlers.onScroll);
		document.observe(this.evtprefix+':carousel:pagechange',this.boundHandlers.onPageChange);
		document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage()});
	},
	getItemTotalWidth: function(ele){
		var retWidth	= 0;
		if(ele){
			retWidth 	= ele.getWidth();
			var margins	= {left:(parseInt(ele.getStyle('margin-left'))),right:(parseInt(ele.getStyle('margin-right')))};

			if(margins.left > 0){retWidth = retWidth+margins.left;}
			if(margins.right > 0){retWidth = retWidth+margins.right;}
		}
		return retWidth
	},
	onPageChange: function(event){
		if(this.container.identify() == event.memo.id){
			this.console.info('nfl.carousel.onPageChange: '+event.memo.id+' {'+this.evtprefix+':carousel:pagechange'+'}');
			var currentPageEle	= this.container.select('.carousel-controls-page').first();
			var totalPagesEle	= this.container.select('.carousel-controls-totalpages').first();
			this.portwidth 	= this.container.getWidth()+ Math.abs(this.originalLeftMargin);
			// this.console.info('nfl.photos.carousel.onPageChange: '+
			// this.totalWidth +' / '+ portwidth +' = '+
			// (Math.floor(this.totalWidth / portwidth)));
			// this.console.info('nfl.photos.carousel.onPageChange: '+
			// this.container.identify() +' total pages = '+
			// (Math.floor(this.totalWidth / portwidth)) +', current page = '+
			// this.getCurrentPage());

			if(totalPagesEle){totalPagesEle.update(this.getTotalPages());}
			if(currentPageEle){currentPageEle.update(((typeof event.memo.page !== 'undefined')?(event.memo.page):this.getCurrentPage())+'');}
		}
	},
	getTotalPages: function(){
		if(this.totalPages === -1){
			if(!isNaN(Math.ceil(this.totalWidth / this.portwidth))){
				this.totalPages	= Math.ceil(this.totalWidth / this.portwidth);
				// this.console.info('nfl.photos.carousel.getTotalPages: is
				// ie?'+ Prototype.Browser.IE +',
				// version='+Prototype.Browser.Version);
			}
			if(this.totalPages < 1){
				this.totalPages	= 1;
			}
		}
		return this.totalPages
	},
	getCurrentPage: function(floor){
		var itemcontainer	= this.list;
		var portwidth 		= this.container.getWidth();
		var floor			= (typeof floor === 'undefined')?false:floor;
		// console.log('getCurrentPage: '+portwidth);
		// console.log('getCurrentPage:
		// '+(parseInt(itemcontainer.getStyle('margin-left')) / portwidth));
		var retval			= (floor)?(Math.floor(Math.abs(parseInt(itemcontainer.getStyle('margin-left'))) / portwidth)+1):Math.ceil(Math.abs(parseInt(itemcontainer.getStyle('margin-left'))) / portwidth)+1;
		// console.log('getCurrentPage: '+retval);
		return retval;
	},
	getPageByOffset: function(left){
		try{
			var itemcontainer	= $(this.containerId);
			var portwidth 		= itemcontainer.up().getWidth();
			var mleft			= (typeof left == 'undefined')? parseInt(itemcontainer.getStyle('margin-left')):left;
			return Math.ceil(Math.abs(mleft) / portwidth);
		}catch(e){ console.warn('nfl.photogallery.thumbnails.getPage: error',e); }
		try{
			// return Math.floor(this.__currentItem.index /
			// this.numberOfThumbsPerScrollPanel)
		}catch(e){}

		return 0;
	},
	canScrollLeft: function(){
		if(this.getCurrentPage() > 1){ return true }
		return false
	},
	scrollLeft: function(){
		document.fire(this.evtprefix+':carousel:scroll',{'id':this.container.identify(),'direction':'left'});
	},
	canScrollRight: function(){
		if(this.getCurrentPage() < this.getTotalPages()){ return true }
		return false
	},
	scrollRight: function(event){
		document.fire(this.evtprefix+':carousel:scroll',{'id':this.container.identify(),'direction':'right'});
	},
	scrollToPageByIndex: function(index){
		// first get item
		var __items	= this.list.select('li');
		if(__items.length > 0 && (index - 1) < __items.length){
			var __item		= __items[(index - 1)];
			var __iOffset	= __item.viewportOffset()[0];
			var __cOffset	= this.list.viewportOffset()[0];
			var __left		= (__cOffset < 0)?((__iOffset < 0)?(Math.abs(__cOffset) - Math.abs(__iOffset)):(Math.abs(__cOffset) + __iOffset)):(__iOffset - __cOffset);
			var __page		= Math.floor(Math.abs(__left) / this.portwidth);
			if(__left < this.portwidth){
				__page		= 0;
			}
			var __nLeft		= (__page * this.portwidth);
			this.list.morph('margin-left: -' + __nLeft + 'px;',{afterFinish: function(){document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage()});}.bind(this), duration: .8, fps: 30});

			return
		}
		console.log('scrollToPageByIndex: out of bounds '+index+'x'+__items.length);
	},
	scrollToIndex: function(index){
		var __items	= this.list.select('li');
		if(__items.length > 0 && (index - 1) < __items.length){
			this.relativePaging = true;
			var __item		= __items[(index - 1)];
			var __iOffset	= __item.viewportOffset()[0];
			var __cOffset	= this.list.viewportOffset()[0];
			var __left		= (__cOffset < 0)?((__iOffset < 0)?(Math.abs(__cOffset) - Math.abs(__iOffset)):(Math.abs(__cOffset) + __iOffset)):(__iOffset - __cOffset);
			this.list.morph('margin-left: -' + __left + 'px;',{afterFinish: function(){document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage(true)});}.bind(this), duration: .8, fps: 30});

			return
		}
	},
	scrollToPage: function(page){
		if(page > 0 && page < this.getTotalPages()){
			__left	= (page > 1)?(0 - (this.portwidth * (page - 1))):0;
			if(this.options.slide){
				this.list.morph('margin-left:' + __left + 'px;',{afterFinish: function(){document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage(true)});}.bind(this), duration: .8, fps: 30});
			}else{
				this.list.setStyle({'marginLeft': __left + 'px'});
				document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage()});
			}
		}
	},
	onScroll: function(event){
		this.console.info("nfl.carousel.onScroll");
		if(this.container.identify() == event.memo.id){
			var amountToScroll				= 0;
			var amountToScrollMultiplyer	= this.scrollMultiplyer;
			var direction 					= event.memo.direction;
			var itemcontainer				= this.list;
			// portwidth = this.container.getWidth()+
			// Math.abs(this.originalLeftMargin);
			var portwidth 					= parseInt(this.container.getStyle('width'))+ Math.abs(this.originalLeftMargin);
			var newCoord					= 0;

			if(event.memo.multiplyer){ amountToScrollMultiplyer	= event.memo.multiplyer;}
			/*
			 * try{ var itemLeft =
			 * parseInt(itemcontainer.getStyle('margin-left')); }catch(e){
			 * itemcontainer.setStyle({'margin-left':'0px'}); var itemLeft =
			 * parseInt(itemcontainer.getStyle('margin-left')); }
			 */
			var cpage	= this.getCurrentPage();
			if(this.relativePaging){
				var cLeft	= parseInt(this.list.getStyle('margin-left'));
				switch(direction){
					case 'left':
						newCoord 	= ((0 - (Math.abs(cLeft) - portwidth)) < 0)?(0 - (Math.abs(cLeft) - portwidth)):((cLeft < 0)?0:(0-((this.getTotalPages()-1) * portwidth)));
						if(newCoord == 0){ this.relativePaging = false; }
						break;
					case 'right':
						newCoord 	= ((0 - (Math.abs(cLeft) + portwidth)) > (0-(parseInt(this.list.getStyle('width')) - portwidth)))?(0 - (Math.abs(cLeft) + portwidth)):(((0-(parseInt(this.list.getStyle('width')) - portwidth)) > (0-((this.getTotalPages()-1) * portwidth)) )?(0-(parseInt(this.list.getStyle('width')) - portwidth)):0);
						if(newCoord == 0){ this.relativePaging = false; }
						break;
					default:
						break;
				}
			}else{
				switch(direction){
					case 'left':
						// newCoord = (itemLeft ==
						// (0+this.originalLeftMargin))?(0 - (portwidth *
						// Math.floor((this.totalWidth -
						// Math.abs(this.originalLeftMargin)) /
						// portwidth))):(Math.abs(itemLeft) - portwidth);
						newCoord 	= (cpage == 1)?(0-((this.getTotalPages()-1) * portwidth)):(0-((cpage-2)*portwidth));
						break;
					case 'right':
						newCoord 	= (cpage == this.getTotalPages())? 0:(0-((cpage)*portwidth));
						// newCoord = ((Math.abs(itemLeft) + portwidth) <=
						// this.totalWidth)?(0 - (Math.abs(itemLeft) +
						// portwidth)):(0 + this.originalLeftMargin);
						break;
					default:
						break;
				}
			}
			// now perform scroll operation based on value outputs from switch
			// statement above
			if(Math.abs(newCoord) % portwidth == (0+this.originalLeftMargin) || this.relativePaging){
				// newLeft = (itemLeft + amountToScroll);
				this.console.log("{nfl.carousel.onScroll: newCoord = "+ newCoord +"}");
				if(this.options.slide){
					itemcontainer.morph('margin-left: ' + newCoord + 'px;',{afterFinish: function(){document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage()});}.bind(this), duration: .8, fps: 30});
				}else{
					itemcontainer.setStyle({'marginLeft':newCoord + 'px'});
					document.fire(this.evtprefix+':carousel:pagechange',{id:this.container.identify(),page:this.getCurrentPage()});
				}
			}else{
				this.console.warn('nfl.carousel.onScroll: item is in play.');
				// nfl.log("{nfl.carousel.onScroll: item is in play: "+ itemLeft
				// +" % "+ portwidth +" == "+ (itemLeft % portwidth ==
				// (0+this.originalLeftMargin)) +"}");
			}
		}
	},
	destroy:function(){
		// document.stopObserving(this.evtprefix+':carousel:scroll',
		// this.boundHandlers.onScroll);
		// document.stopObserving(this.evtprefix+':carousel:pagechange',
		// this.boundHandlers.onPageChange);
		document.stopObserving(this.evtprefix+':carousel:scroll');
		console.info('nfl.carousel.destroy: destroyed');
	}
});

nfl.widgets.DynamicTitles = (function(){
	var __titleIds	= [];
	var addTitle	= function(id,opts){
		opts		= (typeof opts !== 'undefined')? opts : {};
		__titleIds[__titleIds.length] = {'id':id,'opts':opts};
		console.log('nfl.widgets.DynamicTitles.addTitle('+id+','+opts+')',__titleIds);
	}
	var onLoaded	= function(event){
		/* for each item in collection, replace with swf */
		__titleIds.each(function(__title){
			/* get element */
			try{
			var __ele	= $(__title.id);
			var __txt	= __ele.innerHTML;
			var __dims	= __ele.getDimensions();
			var __o		= {h:__dims.height,w:__dims.width,fp:((typeof __title.opts.asset !== 'undefined')? __title.opts.asset : (nfl.global.flashpath + "/flash/utils/ezSlabBold.swf"))};
			__o			= Object.extend(__o, __title.opts);
			console.log('nfl.widgets.DynamicTitles.onLoaded: ',__ele,__txt,__o);
			var __so	= new SWFObject(__o.fp, __title.id+'-swf', __o.w, __o.h, "9.0.115", "#FFFFFF", true);
			__so.addParam('allowScriptAccess', 'always');
			__so.addParam('allowFullScreen', 'false');
			__so.addParam('salign', 'lt');
			__so.addParam('align', 'left');
			__so.addParam('wmode', 'transparent');
			__so.addVariable('txt', __txt);

			__so.write(__title.id);
			}catch(e){ console.warn('nfl.widgets.DynamicTitles.onLoaded',e); }
		})
	}
	document.observe('dom:loaded',onLoaded);

	return {
		add: function(id,opts){
			addTitle(id,opts)
		}
	}
})()

