/*************************** 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 
});
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){deerfest.log(e.message)}}
Object.extend(Prototype.Browser,{Version: (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[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();
	}
	function watchForHashChange(){
		try {
			window.__hash = location.hash;
			hashChecker = setInterval(hasHashChanged, 200);
		} catch(e) {}
	}
	Event.observe(window, 'hashchange', checkHashChange);
	document.observe('dom:loaded', watchForHashChange);
})();
window.location.hashparams = function(){
	return {
		getStringFromHash: function(oHash){
			var retStr = '', hashObj = $H(oHash);
			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 +'/');
					}
				}
			});
			return (retStr.substring(0,retStr.length - 1));
		},
		getHashFromString: function(stringObj){
			//deerfest.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);
		}
	}
}()
if (!window.console || !console.firebug){
	if(document.cookies.get('debug') == 'true'){ 
		document.include('http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');
	}else{
		var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
		window.console = {}; for (var i = 0; i < names.length; ++i){ window.console[names[i]] = function() {}}
	}
}
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 deerfest=="undefined"){ var deerfest={}; } 
/**
 * Creates new namespaces under the deerfest namespace
 * @param {String} The name of the new namespace
 */
deerfest.namespace=function(){ var a=arguments,o=null,i,j,d;for(i=0;i<a.length;++i){d=a[i].split(".");o=deerfest;for(j=(d[0]=="deerfest")?1:0;j<d.length;++j){o[d[j]]=o[d[j]]||{};o=o[d[j]];}} return o;};
deerfest.namespace("ui","util","global","data","analytics");
deerfest.global.debugenabled	= true;
deerfest.global.SEARCH_ADS	= true;
/**
 * Writes a message to the console(if available)
 * @param {String} message The message to write
 */
deerfest.log=function(message,type){
	try{ console.log(message); }catch(err){}
}; deerfest.log("loading deerfest.js..");
/**
 * Loads in the enviromental variables defined in the commons_js
 */
deerfest.global.imagepath			= n_imagepath;
deerfest.global.scriptpath			= n_scriptpath;
deerfest.global.flashpath			= n_flashpath;
deerfest.global.ENV                  = n_environment;
deerfest.global.ecmimagepath			= (typeof n_ecmimagepath !== 'undefined')?n_ecmimagepath:'';
if(typeof n_searchdomain != 'undefined'){
	deerfest.global.searchdomain			= (n_searchdomain.indexOf(':') > -1)? n_searchdomain.substring(0,n_searchdomain.indexOf(':')):n_searchdomain;
}else{
	deerfest.global.searchdomain			= 'search.deerfest.com'; /*just hardcode to prod search */
}
deerfest.global.SITELIFE_URL			= typeof n_sitelife === 'undefined' ? 'http://pluck.deerfest.com' : n_sitelife;
/**
 * document.domain is required for third-party integration (sitelife)
 * Sets any sub-domain of deerfest.com to deerfest.com, but does not affect localhost
 **/
try { 
	document.domain = window.location.hostname.match(/([^\.\/]*\.?[^\.\/]+)$/)[1];
} catch(err) {}
/**
 * Initialize deerfest.util.cookies namespace 
 * note: these functions have been moved to document.cookies. these references are just pointers now. (a.w.)
 */
deerfest.namespace("util.cookies"); deerfest.util.cookies.getCookieVal = document.cookies.getValue; deerfest.util.cookies.getExpDate = document.cookies.getExipiry; deerfest.util.cookies.getCookie = document.cookies.get; deerfest.util.cookies.setCookie = document.cookies.set; deerfest.util.cookies.deleteCookie = document.cookies.remove; var getExpDate = document.cookies.getExipiry; var getCookieVal = document.cookies.getValue; var getCookie = document.cookies.get; var setCookie = document.cookies.set; var deleteCookie = document.cookies.remove;
deerfest.namespace('deerfest.events');
/**
 * Enables Flash to fire prototype custom events.
 */
deerfest.events.fire      = function( _type, _memo ) { document.fire( _type, _memo ); } 
deerfest.events.available = function() { return true; }
/**
 * functions and properties for manipulating ads
 * @author arianna.winters
 * @namespace deerfest
 * @requires deerfest
 */
deerfest.namespace("deerfest.ads");
deerfest.ads.collection	= [];
deerfest.ads.visibleAds	= 0;
deerfest.ads.hasRotating = false;
deerfest.ads.rotationInterval = 30;
deerfest.ads.internal	= (typeof n_internal_ads !== 'undefined')?n_internal_ads:false;
/**
 * ad object
 * @author arianna.winters
 * @namespace deerfest.ads
 * @class deerfest.ads.Ad
 * @requires deerfest.ads
 */
deerfest.ads.Ad	= Class.create();
deerfest.ads.Ad.prototype	= {
	initialize: function(div, params, options) {
		this.pathOnly = (options.pathOnly)?true:false;
		this.params	= params;
		this.options = (typeof options === 'undefined')?{}:options;
		this.tile	= (deerfest.ads.collection.length + 1)
		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	= (deerfest.ads.visibleAds + 1);
			var el, count, url;
			if(!div.id){ div, this.tile }
			el			= $(div);
			el.addClassName('ad'+this.adClassInt);
			this.id		= (el.id + '-iframe') || ("ad" + this.adClassInt +'-iframe');
			if(this.options.write){el.innerHTML = this.getIframeHTML();}
			deerfest.ads.add(this);
			el = null;
		}else{
			this.adClassInt	= false;
			deerfest.ads.add(this);
			return (this.params.replace('#{tile}',this.tile) +';ord=' + adRandom + '?');
		}
	},
	getInternal: function(){
		if(typeof deerfest.ads.internal !== 'undefined'){
			for(var adi=0,adl=deerfest.ads.internal.length; adi < adl; adi++){
				var matchesAll	= (deerfest.ads.internal[adi].length > 0)?true:false;
				for(var adifl=0; adifl < deerfest.ads.internal[adi].length; adifl++){
					var match	= deerfest.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.deerfest.com/widgets/ads-served-by-deerfest/' + 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() {
		//deerfest.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')});
		}
	}
}
deerfest.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('deerfest.ads.rotate');
		var __log	= '';
		deerfest.ads.random(); //first update the adRandom var
		deerfest.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('deerfest.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 && deerfest.ads.rotationInterval > __elapsed){
				/* start from last spot */
				var sp	= (deerfest.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;}
	}
}))();

deerfest.ads.add	= function(Ad){
	var adIndex	= deerfest.ads.collection.length;
	deerfest.ads.collection.each(function(Adi,ind){
		if(Adi.id == Ad.id){adIndex = ind; throw $break;}
	}.bind(this));
	
	if(!Ad.pathOnly){
		if(Ad.rotate == true){ 
			deerfest.log("ad #"+ Ad.adClassInt +" is a rotating ad"); 
		}else{
			deerfest.log("ad #"+ Ad.adClassInt +" is not a rotating ad"); 
		}
		if(Ad.rotate == true && deerfest.ads.hasRotating == false){
			/* has not had any previous rotating ads */
			deerfest.ads.hasRotating	= true;
			if(document.loaded){ deerfest.ads.rotation.start(); }else{ document.observe("dom:loaded",function(){ deerfest.ads.rotation.start(); }); }
		}
		if(adIndex === deerfest.ads.collection.length){ deerfest.ads.visibleAds++; }
	}
	deerfest.ads.collection[adIndex] = Ad;
}
deerfest.ads.replace = function(Ad){
	var adIndex	= -1;
	deerfest.ads.collection.each(function(Adi,ind){
		if(Adi.id == Ad.id){adIndex = ind; throw $break;}
	}.bind(this));
	if(adIndex > -1){
		deerfest.ads.collection[adIndex] = Ad;
	}
}
deerfest.ads.getById = function(id){
	var retAd	= null;
	deerfest.ads.collection.each(function(Adi,ind){
		//console.log('deerfest.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}
 */
deerfest.ads.random	= function(){ adRandom	= (Math.random() * 1000); return adRandom; };
deerfest.ads.random();

/**
 * Image Preloading functions.
 */
deerfest.namespace("deerfest.util.images.preloader");
deerfest.util.images.preloader.notFoundImg	= null;
deerfest.util.images.preloader.checks		= {generic: function(image){ image.src = notFoundImg.src; }};
deerfest.util.images.preloader.loadImages	= function(){ 
	var imagesToPreload = arguments; var preloadedImages = [];
	for(var i = 0; i < imagesToPreload.length; i++) { preloadedImages[i] = document.createElement('img'); preloadedImages[i].src = imagesToPreload[i];} return preloadedImages;
};
deerfest.util.images.preloader.loadImages2	= function(){
	var imagesToPreload = arguments[0]; var preloadedImages = [];
	for(var i = 0; i < imagesToPreload.length; i++) { preloadedImages[i] = new Image(); preloadedImages[i].src = imagesToPreload[i]; } return preloadedImages;
};
deerfest.util.images.preloader.loadImages3	= function() {
	var imagesToPreload = arguments[0]; var preloadedImages = [];
	for(var i = 0; i < imagesToPreload.length; i++) { var c = i + 1; $('sr_image' + c).src = imagesToPreload[i]; } return preloadedImages;
};
var preloadImages		= deerfest.util.images.preloader.loadImages; var preloadImages2	= deerfest.util.images.preloader.loadImages2; var preloadImages3	= deerfest.util.images.preloader.loadImages3;
/**
 * 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
 */
deerfest.util.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();
};
var $openWindow	= deerfest.util.openPopWindow; //shorthand pointer
/**
 * 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.
 */
deerfest.util.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);
};
/**
 * Methods for creating and updating the scorestrip
 * @author ryan.cannon
 * @namespace deerfest.global
 * @class Scorestrip
 * @requires swfobject, deerfest
 */
deerfest.global.Scorestrip = Class.create();
deerfest.global.Scorestrip.prototype = {
	/**
	 * 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:{};
		var validSubDomains	= [
			                 	  'local.deerfest.com',
			                 	  'dev.www.deerfest.com',
			                 	  'test.www.deerfest.com',
			                 	  'stage.www.deerfest.com',
			                 	  'origin-dev.www.deerfest.com',
			                 	  'origin-test.www.deerfest.com',
			                 	  'origin-stage.www.deerfest.com',
			                 	  'origin-prod.www.deerfest.com',
			                 	  'testweb01.la3.deerfest.com',
			                 	  'testapp01.la3.deerfest.com',
			                 	  'stageweb01.la3.deerfest.com',
			                 	  'stageweb02.la3.deerfest.com',
			                 	  'stageweb03.la3.deerfest.com',
			                 	  'stageweb04.la3.deerfest.com',
			                 	  'stageapp01.la3.deerfest.com',
			                 	  'stageapp02.la3.deerfest.com',
			                 	  'stageapp03.la3.deerfest.com',
			                 	  'stageapp04.la3.deerfest.com',
			                 	  'stageapp05.la3.deerfest.com',
			                 	  'stageapp06.la3.deerfest.com',
			                 	  'stageapp07.la3.deerfest.com',
			                 	  'prodweb01.la3.deerfest.com',
			                 	  'prodweb02.la3.deerfest.com',
			                 	  'prodweb03.la3.deerfest.com',
			                 	  'prodweb04.la3.deerfest.com',
			                 	  'prodweb05.la3.deerfest.com',
			                 	  'prodweb06.la3.deerfest.com',
			                 	  'prodweb07.la3.deerfest.com',
			                 	  'prodweb08.la3.deerfest.com',
			                 	  'prodapp01.la3.deerfest.com',
			                 	  'prodapp02.la3.deerfest.com',
			                 	  'prodapp03.la3.deerfest.com',
			                 	  'prodapp04.la3.deerfest.com',
			                 	  'prodapp05.la3.deerfest.com',
			                 	  'prodapp06.la3.deerfest.com',
			                 	  'prodapp07.la3.deerfest.com',
			                 	  'prodapp08.la3.deerfest.com',
			                 	  'prodapp09.la3.deerfest.com',
			                 	  'prodapp10.la3.deerfest.com',
			                 	  'prodapp11.la3.deerfest.com',
			                 	  'prodapp12.la3.deerfest.com',
			                 	  'prodapp13.la3.deerfest.com',
			                 	  'prodapp14.la3.deerfest.com'
			                 	  ];
		this.opts.flashVars['baseURL'] = (window.location.host.match(/(?:[^\/]+)\.deerfest\.com/) && validSubDomains.indexOf(window.location.hostname) == -1) ? window.location.protocol + '//www.deerfest.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 deerfest.media.Flash(deerfest.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 deerfest.events
 * @class AuthenticationEvent
*/
deerfest.events.AuthenticationEvent = function () {
	var AE, prefix;
	prefix = 'deerfest: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); console.log(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(deerfest.events.AuthenticationEvent.SIGN_IN, doSomething);
 *
 * In order to be logged in, you must have all three deerfest cookie: userId, at & ptnr.
 * 
 * @namespace deerfest.global
 * @class Authentication
 */
deerfest.global.Authentication = function () {
	var AuthenticationEvent = deerfest.events.AuthenticationEvent,
	    Cookies			= { USER: 'userId', SITELIFE: 'at', PARTNER: 'ptnr' },
	    COMPONENT		= 'AuthenticationEvent',
	    DOMAIN			= document.domain,
	    PATH			= '/',
	    COOKIE_SIGN_IN	= 'CookieSignIn',
	    deerfestCookie       = document.cookies.get(Cookies.USER).toQueryParams(),
	    pluckCookie     = document.cookies.get(Cookies.SITELIFE).toQueryParams(),
	    partnerCookie   = document.cookies.get(Cookies.PARTNER).toQueryParams(),
	    team, username;
	
	if (deerfestCookie.u) {
		team			= decodeURIComponent(deerfestCookie.t);
		username		= decodeURIComponent(deerfestCookie.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()) {
			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 deerfest.global
 * @class Header
 * @requires deerfest.global.Authentication
 */
deerfest.global.Header = function(){
	var AuthenticationEvent = deerfest.events.AuthenticationEvent;
	var 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'
	};
	// Retrieves the last section of the url before a query string
	var USER_REGEXP = /\/([^\/\?#]*)(([#\?][^#\?]*){0,2})$/;
	var initialized = false;

	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, profileLink;
			profile				= $(ID.PROFILE);
			profileLink			= profile.select('a').first();
			profileLink.href	= profileLink.href.replace(USER_REGEXP, "/" + e.memo.username + "$1");

			initialized = true;

			$(ID.SIGN_IN, ID.REGISTER).invoke('hide');
			$(ID.SIGN_OUT, profile).invoke('show');
		}
		catch(e) { killHeaderLinks(e);}
	}
	
	function onSignOut() {
		try {
			var profile, profileLink;
			profile				= $(ID.PROFILE);
			profileLink			= profile.select('a').first();
			profileLink.href	= profileLink.href.replace(USER_REGEXP, "/$1");

			$(ID.SIGN_IN, ID.REGISTER).invoke('show');
			$(ID.SIGN_OUT, profile).invoke('hide');
		}
		catch(e) { killHeaderLinks(e); }
	}
	function killHeaderLinks(e) {
		deerfest.log("deerfest.global.Header could not locate loginButtons");
		deerfest.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 deerfest.global
 * @class Decorators
 */
deerfest.global.Decorators = function() {
	// initialize at page load
	document.observe('dom:loaded',initialize);
	
	function initialize() {
		var el = $('copyright');
		if (! el) { return;}
		deerfest.global.Decorators.add(el, ['bl', 'br'], false);
		var els = $$('div.shadowed').each(deerfest.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 deerfest.global
 * @class Footer
 */
deerfest.global.Footer = Class.create();
deerfest.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 deerfest.media.Flash(deerfest.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 deerfest.global
 * @class CenterPiece
 */
deerfest.global.CenterPiece = Class.create();
deerfest.global.CenterPiece.prototype = {
	/**
	 * 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: deerfest.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 deerfest.media.Flash(flashURL, div, o.merge($H(options || {})));
	},
	getFlash: function() { return this.flash }
}
deerfest.namespace("deerfest.media");
deerfest.media.Flash = Class.create();
deerfest.media.Flash.prototype = {
	initialize: function(url, el, options) {
		var so, id, o, fID;
		//deerfest.log("deerfest.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 */
		//deerfest.log("deerfest.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();
		//deerfest.log("deerfest.media.Flash.initialize: 3");
		//deerfest.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){}
			}
		}
		//deerfest.log("deerfest.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)) });
		//deerfest.log("deerfest.media.Flash.initialize: 5");
		so.write(id);
		so = null;
		//deerfest.log("deerfest.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 
 */
deerfest.namespace('deerfest.media.audio');
deerfest.media.audio.player = function(contentId){
	var pageToOpen = "/audioplayer?id=" + contentId; // http://www.deerfest.com/audioplayer?id=09000d5d802c2ec8
	$openWindow(pageToOpen, 'audioPlayer', {width:760,height:410,toolbar:0,scrollbar:'auto'});
}

/* event logging */
document.observe('dom:loaded',function(){ deerfest.log("{dom:loaded}"); });
document.observe('dom:beforeloaded',function(){ deerfest.log("{dom:beforeloaded}"); });
document.observe('dom:ready',function(){ deerfest.log("{dom:ready}"); });
document.observe('window:hashchange',function(){ deerfest.log("{window:hashchange}"); });

deerfest.namespace("deerfest.bandages");
deerfest.bandages.IE6BackgroundImageFix = (function(){
	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;
})();
deerfest.bandages.IEDoesNotSupportABBRUntilThis = function () { document.createElement('abbr');}();
deerfest.bandages.IE6HeaderFixes = Class.create();
deerfest.bandages.IE6HeaderFixes.prototype = {
	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");
			deerfest.bandages.IE6NavigationId = (typeof options['navId'] == 'undefined')?'nav':options['navId']; 	
			var nav = document.getElementById(deerfest.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(deerfest.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==deerfest.bandages.IE6NavigationId) && (this.getElementsByTagName("UL").length != 0) ){ ie6CoverDropDowns(this, 'mouseover'); }
		}
		function onRollOut(e){
			if($(this).hasClassName("sfhover")){ $(this).removeClassName("sfhover"); }
			if((this.parentNode.id==deerfest.bandages.IE6NavigationId) && (this.getElementsByTagName("UL").length != 0) ){ ie6CoverDropDowns(this, 'mouseout'); }
		}
	}
};
deerfest.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='" + deerfest.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) {}
	}
};
deerfest.namespace('widgets');
/**
 * The VideoPlayer class allows embedding of the deerfest video player. 
 *
 * @namespace deerfest.widgets
 * @class VideoPlayer
 */
deerfest.widgets.VideoPlayer = (function(){

	var OPTIONAL_ARGUMENTS   = $w('contentId companionSize related playerName adSetting adRatio dartURL autoplay channelId');
	var ALT_CONTENT_TEMPLATE = new Template(
	        '<div id="#{id}" style="visibility:hidden">' +
	                '<a href="http://get.adobe.com/flashplayer/" target="_blank">' + 
	                        '<img src="' +
	                        deerfest.global.imagepath +
	                        '/img/video/flash-required-#{w}x#{h}.png" alt="Flash is required to watch videos on deerfest.com. Please click here to install Flash on your computer." />' +
	                '</a>' +
	        '</div>'
	);
	
	function getSizeOptions( size ) {
		switch( size ) {
			case 'large':    return { w: '615', h: '346', f: 'large-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' };
		}
	}
	
	return Class.create({
		initialize: function( config ) {

			var sizeOptions, so, id, divid, swfid, container, div;

			id = config.uniqid || config.contentId;
			if ( /^\d/.test(id) ) {
				id = 'v' + id;
			}
			divid = id + '-video';
			this.swfid = id.replace(/-/g, '') + 'swf';
			o     = getSizeOptions( config.size );
			if ( config.width ) {
				o.w = config.width;
			}
			if ( config.height ) {
				o.h = config.height;
			}
			o.id  = divid;
			so    = new SWFObject(
				deerfest.global.flashpath + "/flash/video/" + o.f + ".swf",
				this.swfid, o.w, o.h, "9.0.115", "#000000", true
			);
			so.useExpressInstall(deerfest.global.flashpath + "/flash/expressinstall.swf");
			so.addParam('allowScriptAccess', 'always');
			so.addParam('allowFullScreen', 'true');
			so.addParam('wmode', 'opaque');
			so.addVariable('uniqid', this.swfid);
			OPTIONAL_ARGUMENTS.each(function(arg) {
				if (config[arg]) { so.addVariable(arg, config[arg]); }
			});
			this.so = so;
			if ( config.containerId && (container = $( config.containerId )) ) {
				divid = container.identify();
			}
			else if ( config.write === false ) {
                return;
			}
            else {
            	document.write( ALT_CONTENT_TEMPLATE.evaluate( o ) );
            }
            setTimeout(function() {
            	so.write(divid);
           		$(divid).style.visibility = "visible";
            }, 50);
		},
		instance: function() {
			return $( this.swfid );
		}
	});
}());
deerfest.widgets.VideoPlayers = {};

/*
 * @author arianna.winters
 * @class deerfest.widgets.Carousel
 * @param {String} | {Object} parent container element of ul element
 */
deerfest.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:'deerfest';
		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('deerfest.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('deerfest.photos.carousel.onPageChange: '+ this.totalWidth +' / '+ portwidth +' = '+ (Math.floor(this.totalWidth / portwidth)));
			//this.console.info('deerfest.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('deerfest.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('deerfest.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("deerfest.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("{deerfest.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('deerfest.carousel.onScroll: item is in play.');
				//deerfest.log("{deerfest.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('deerfest.carousel.destroy: destroyed');
	}
});

deerfest.widgets.DynamicTitles = (function(){
	var __titleIds	= [];
	var addTitle	= function(id,opts){
		opts		= (typeof opts !== 'undefined')? opts : {};
		__titleIds[__titleIds.length] = {'id':id,'opts':opts};
		console.log('deerfest.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 : (deerfest.global.flashpath + "/flash/utils/ezSlabBold.swf"))};
			
			console.log('deerfest.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('deerfest.widgets.DynamicTitles.onLoaded',e); }
		})
	}
	document.observe('dom:loaded',onLoaded);
	
	return {
		add: function(id,opts){
			addTitle(id,opts)
		}
	}
})()

