if ( Object.isUndefined(nfl) ){  var nfl = { community: {} }; }
nfl.community = (function(){
	var BM, IMAGE_TEMPLATE  = new Template('<img src="#{src}" alt="#{alt}" />'),
	    PARAM_RE, STARS_CSS = "span.score span.value",
	    NO_USER_IMAGE_RE    = /\/images\/no\-user\-image\.gif$/,
	    NO_USER_IMAGE       = nfl.global.imagepath + '/img/community/profile/no-avatar.png',
	    PROFILE_BASE            = '/registration',
	    PROFILE_PATH            = PROFILE_BASE + '/profile/',
		SECTION                 = {
			MESSAGES: '/shout-outs',
			ACTIVITY: '/activity',
			SETTINGS: '/settings',
			EDIT:     '/edit-profile',
			FRIENDS:  '/friends'
		};

	function getAvatarImage (_user) {
		return IMAGE_TEMPLATE.evaluate({ src: NO_USER_IMAGE_RE.test(_user.AvatarPhotoUrl) ? NO_USER_IMAGE : _user.AvatarPhotoUrl, alt: "" })
	}
	
	function profileURL(_user, _section) {
		return Object.isUndefined(_section) ?
			PROFILE_PATH + _user :
			(_section === SECTION.EDIT || _section === SECTION.SETTINGS) ? 
				PROFILE_BASE + _section :
				PROFILE_PATH + _user + _section;
	}

	return {
		PlayerRatings: (function () {
			var el, list, template, options, SCORE_WIDTH = 63, MAX_RATING = 5,
			    className = "even";
			
			function onUnload (_e) {
				el = list = null;
			}
			
			function compileHTML (_acc, _article) {
				var title     = _article.PageTitle.split('||'),
				    id        = _article.ArticleKey.Key.split('-')[3],
				    playerImg = nfl.global.ecmimagepath +
					       '/public/image/getty/headshot/' +
					       id.substr(0,1) + '/' + id.substr(1,1) + '/' + id.substr(2,1) +
					       '/' + id + '.jpg';
				className     = className === "even" ? "odd" : "even";
				return _acc + template.evaluate({
					className: className,
					headshotImg: IMAGE_TEMPLATE.evaluate({
						src: playerImg,
						alt: "Photo of " + title[0]
					}),
					name: title[0],
					position: title[1],
					stats: title[2],
					stars: Math.round( parseFloat(_article.Ratings.AverageRating, 10) * 10) / 10,
					url: _article.PageUrl
				});
			}
			
			function setStarScore(_span) {
				_span.setStyle({ width: Math.round(parseFloat(_span.getAttribute('title'), 10) / MAX_RATING * 100) + '%' });
			}
			
			function onDiscoveredContent (_response) {
				var dca, dc;
				
				dca = BM.find(_response, 'DiscoverContentAction');
				if ( Object.isUndefined(dca) || dca.DiscoveredContent.length === 0 ) {
					list.update('').hide();
					el.hide();
					return;
				}
				list.update(dca.DiscoveredContent.inject('', compileHTML)).show();
				list.select(STARS_CSS).each(setStarScore);
			}
			
			function getPlayerRatings (e) {
				if ( Object.isUndefined(BM) ) {
					BM = nfl.sitelife.BatchManager;
				}
				BM.discoverContent(options, onDiscoveredContent);
			}
			
			return function(_config) {
				el       = $(_config.el);
				list     = $(_config.list);
				template = list.templatize();
				options  = {
					activity: 'Rated',
					section: "gcplayerratings",
					categories: [ _config.week ]
				};
				
				Event.observe(window, 'unload', onUnload);
				document.observe('dom:loaded', getPlayerRatings);
			};
		}()),
		ProfileOrJoin: (function () {
			var AE = nfl.events.AuthenticationEvent,
			    DEFAULT_STYLE = { backgroundImage: null, backgroundPosition: null },
			    signInEvent, anonymousView, signedInView, template,
			    MESSAGE_TO_RE = /Message to: ([^\s]*)/;
			
			function onSignIn (e) {
				var m = e.memo, uk = new UserKey( e.memo.username );
				if ( m.team.blank() ) {
					m.team = "NFL";
				}
				/*
				m.avatar = IMAGE_TEMPLATE.evaluate({ src: nfl.global.imagepath + '/img/teams/avatars/' + m.team + '.png', alt: '' });
				*/
				BM.AddToRequest( uk, Prototype.emptyFunction );
				BM.AddToRequest( new RecentUserActivity( uk ), function(response) {
					var rua, ua, title;
					
					m.avatar = getAvatarImage(BM.find(response, 'User'));
					
					rua = BM.find(response, 'RecentUserActivity');
					if ( ! rua || rua.UserActivities.length === 0 ) {
						m.hasLastComment = 'none';
					}
					else {
						m.hasLastComment = 'block';
						ua      = rua.UserActivities[0];
						// use the short title

						// add new activites as they 
						if ( ua.Comment ) {
							m.activity = 'comment';
							m.content  = ua.Comment.CommentBody.truncateAtLastWord(300);
							m.date     = new Date(ua.Comment.PostedAtTime_UTC).toAPStyle(true);
							title      = ua.Title.split('||');
							title      = title[ title.length > 1 ? 1 : 0 ];
							m.title    = title;
							m.url      = ua.Url.replace(PARAM_RE, '');
						}
						else if (ua.PersonaMessage) {
							m.activity = 'shout-out to';
							m.content  = ua.PersonaMessage.Body;
							m.date     = new Date(ua.PersonaMessage.CreatedOn_UTC).toAPStyle(true);
							m.title    = ua.Title.match(MESSAGE_TO_RE)[1];
							m.url      = profileURL(m.title, SECTION.MESSAGES);
						}
					}
					signedInView.update(template.evaluate( m ));
					signedInView.setStyle(
						m.team.blank() ? DEFAULT_STYLE :
						{ backgroundImage: "url(" + nfl.global.imagepath + "/img/community/profile-or-join/" + m.team.toLowerCase() + ".png)",
						  backgroundPosition: "left top" }
					);
					anonymousView.hide();
					signedInView.show();
				});
			}
			function onSignOut(e) {
				signedInView.hide();
				signedInView.setStyle(DEFAULT_STYLE);
				anonymousView.show();
			}
			function onEarlySignIn(e) {
				signInEvent = e;
			}
			function onEarlySignOut(e) {
				signInEvent = null;
			}
			
			// handles premature sign ins/outs
			function onDomLoaded () {
				document.stopObserving(AE.SIGN_OUT, onEarlySignOut);
				document.stopObserving(AE.SING_IN, onEarlySignIn);
				document.observe(AE.SIGN_IN, onSignIn);
				document.observe(AE.SIGN_OUT, onSignOut);
				if ( Object.isUndefined(BM) ) {
					BM = nfl.sitelife.BatchManager;
				}
				if (Object.isUndefined(PARAM_RE)) {
					PARAM_RE = nfl.sitelife.PLUCK_COMMENT_KEY_PARAM;
				}
				if ( signInEvent ) {
					onSignIn(signInEvent);
				}
				signInEvent = null;
			}
			
			function onUnload(e) {
				anonymousView = signedInView = null;
			}
			
			return function( config ) {
			    anonymousView = $( config.anonymous ),
			    signedInView  = $( config.signedIn ),
			    template      = signedInView.templatize();
	
				document.observe(AE.SIGN_IN, onEarlySignIn);
				document.observe(AE.SIGN_OUT, onEarlySignOut);
				Event.observe(window, 'unload', onUnload);
				
				document.observe('dom:loaded', onDomLoaded);
			};
		}()),
		Top10: (function () {
			var videos, news, recutters, filter, team = '', template,
			    videosTemplate, newsTemplate, recuttersTemplate,
			    option     = new Template('<option value="#{abbr}">#{city} #{nickname}</options>'),
			    // Top10Event = { TEAM_CHANGE: 'top10:teamchange' },
			    TOP_10_URL = "/ajax/community/toptenvideos",
			    TEAM_PARAM = "teamAbbr";
	
			function compileNewsHTML(acc, content) {
				return acc + newsTemplate.evaluate({
					index: this.index++,
					headline: content.PageTitle.split('||')[0],
					url: content.PageUrl,
					comments: content.Comments.NumberOfComments,
					plural: parseInt(content.Comments.NumberOfComments, 10) === 1 ? '' : 's'
				});
			}
			
			function compileHTML(video, template, obj) {
				video.index           = obj.index;
				obj.index            += 1;
				video.thumbnail_image = IMAGE_TEMPLATE.evaluate({
					src: video.thumbnail,
					alt: "Watch: " + video.headline
				});
				return template.evaluate(video);
			}
			
			function compileVideosHTML(acc, video) {
				return acc + compileHTML(video, videosTemplate, this);
			}

			function compileRecuttersHTML(acc, video) {
				return acc + compileHTML(video, recuttersTemplate, this);
			}
			
			function sortOnCommentCount (a, b) {
				return b.Comments.NumberOfComments - a.Comments.NumberOfComments;
			}
			
			function updateSection(el, collection, iterator) {
				var up = el.up();
				el.update( collection.inject('', iterator, { index: 0 }) );
				if (collection.length) {
					el.show();
					up.show();
				}
				else {
					up.hide();
					el.hide();
				}
			}

			function onDiscoveredContent( response ) {
				var dca, dc;
	
				dca = BM.find(response, 'DiscoverContentAction');
				if ( ! dca ) { return; }
				dc  = dca.DiscoveredContent;
				
				dc.sort(sortOnCommentCount);
				updateSection(news, dc, compileNewsHTML);
			}
	
			function onFilterChange(_e) {
				var t = $F(filter);
				if (t === team) { return; }
				team = t;
				discoverContent(t);
			}
			
			function onDomLoaded() {
				if ( Object.isUndefined(BM) ) {
					BM = nfl.sitelife.BatchManager;
				}
				filter.observe('change', onFilterChange);
				filter.observe('blur', onFilterChange);
				discoverContent();
			}
			
			function onAjaxContent (transport) {
				var json = transport.responseJSON || transport.responseText.evalJSON(true);
				
				updateSection(videos, json.videos, compileVideosHTML);
				updateSection(recutters, json.recutters, compileRecuttersHTML);
			}
			
			function onNoAjaxContent (transport) {
				updateSection(videos, [], compileVideosHTML);
				updateSection(recutters, [], compileRecuttersHTML);
			}
			
			function discoverContent( _team ) {
				var team, categories = [ 'All' ], parameters = {};
				if ( _team ) {
					categories[0] = parameters[TEAM_PARAM] = _team;
				}
				new Ajax.Request(TOP_10_URL, {
					parameters: parameters,
					method: 'get',
					onSuccess: onAjaxContent,
					onFailure: onNoAjaxContent
				});
				BM.discoverContent({ activity: "Commented", categories: categories, age: 1 }, onDiscoveredContent);
			}
			function getTeamOption(acc, pair) {
				return acc + option.evaluate(pair.value);
			}
			function getCity(_team) {
				var t = _team[1]; 
				return t.city + ' ' + t.nickname;
			}
			function sortByCity(a,b) {
				var aCity = getCity(a), bCity = getCity(b);
				return aCity < bCity ? -1 :
				       aCity > bCity ? 1 :
				       0;
			}
			function onUnload(_e) {
				videos = news = recutters = filter = null;
			}
			
			return function(config) {
				videos            = $(config.videos)
				news              = $(config.news);
				recutters         = $(config.recutters);
				filter            = $(config.filter);
				videosTemplate    = videos.templatize();
				newsTemplate      = news.templatize();
				recuttersTemplate = recutters.templatize();
				
				// Add a teams to filter select sorted by city 
				filter.insert( $H(nfl.data.TEAMS).entries().sort(sortByCity).inject('', getTeamOption ) );
				filter.selectedIndex = 0;
				Event.observe(window, 'unload', onUnload);
				if ( document.loaded ) { onDomLoaded }
				else {
					document.observe('dom:loaded', onDomLoaded);
				}
			};
		}()),
		TopFans: (function() {
			var el, template;
			
			function compileHTML(acc, content) {
				var ft = content.ExtendedProfile.ft;
				if ( ft === undefined || ft.blank() ) { ft = 'NFL'; }
				content.avatar = getAvatarImage(content);
				return acc + template.evaluate(content);
			}
			
			function onDiscoveredContent( response ) {
				var dca, dc;
	
				dca = BM.find(response, 'DiscoverContentAction');
				if ( ! dca ) { return; }
				dc  = dca.DiscoveredContent;
				
				el.update( dc.inject('', compileHTML) );
				el.show();
			}
			
			function onDomLoaded() {
				if ( Object.isUndefined(BM) ) {
					BM = nfl.sitelife.BatchManager;
				}
				BM.discoverContent({ contentType: "Persona", max: 3 }, onDiscoveredContent);
			}
			
			function onUnload(_e) {
				el = null;
			}

			return function(ref) {
				el       = $(ref);
				template = el.templatize();
	
				Event.observe(window, 'unload', onUnload);
	
				if ( document.loaded ) { onDomLoaded(); }
				else {
					// why does this not fire using dom:loaded?
					Event.observe(window, 'load', onDomLoaded);
				}
			};
		}())
	};
}());