nfl.events.HomePageEvent = {
	TEAM_HEADLINES_AVAILABLE: 'team:headlines:available'
};
nfl.namespace('nfl.home');
/**
 * The NflNetworkListings class creates a more dynamic widget for #nfl-network-listings
 * @namespace nfl.home
 * @class NflNetworkListings
 */
nfl.home = {
	NflNetworkListings: function() {
		var MAX = 3;
		var cur;
		// initialize at page load
		// Event.observe(window,'load', function() { initialize() });
		document.observe('dom:loaded',initialize);

		// Activates the selected item. The second param is an optional event, which is stopped.
		function activate (el, e) {
			var div, lis, links, li, link;
			if (e) { Event.stop(e) }
			if (el == cur) { return }
			cur = el;
			div = $("nfl-network-listings");
		
			lis = div.select("li");
			links = div.select(".nav a");
		
			for (var i = 0; i < MAX; i++) {
				li = lis[i];
				link = links[i + 2];
				if (i == el) {
					li.addClassName('active');
					link.addClassName('active');
				} else {
					if (li.hasClassName('active')) { li.removeClassName('active') }
					if (link.hasClassName('active')) { link.removeClassName('active') }
				}
			}
			div = lis = li = links = link = null;
			return cur;
		}

		// Functions for the various buttons on the widget
		var listeners = {
			bPrev: function(e) {
				var newLi = ((cur == 0) ? MAX : cur) - 1; 
				return activate(newLi, e);
			},
			bNext: function(e) {
				var newLi = cur + 1;
				if (newLi == MAX) { newLi = 0 }
				return activate(newLi, e);			
			},
			now: function(e) { return activate(0, e) },
			next: function(e) { return activate(1, e) },
			later: function(e) { return activate(2, e) }
		}
	
		// Creates HTML and assigns event listeners. Called on page load.
		function initialize(e) {
			var div, arr, nav, h2;
			arr = ['bPrev', 'bNext', 'now', 'next', 'later'];
			div = $("nfl-network-listings");
			if (div.select('li').length > 0) {
				nav = document.createElement('div');
				Element.addClassName(nav, 'nav');
				div.appendChild(nav);
				arr.each(function(el) {
					var a, text;
					a = document.createElement('a');
					a.href = "#";
					text = (el == "bPrev") ? '<' : (el == "bNext") ? '>' : el;
					Element.addClassName(a, el);
					a.appendChild(document.createTextNode(text));
					nav.appendChild(a);
					Event.observe(a, 'click', listeners[el]);
					a = null;
				});
				div.addClassName("active");
				div.select("li").first().addClassName('active');
				h2 = div.select("h2").first()
				h2.appendChild(document.createElement('span'));
				h2.addClassName('replaced');
				activate(0);
			}
			div = nav = null;
			return true;
		}
	}(),
	AnalysisOpinions: function() {
		document.observe('dom:loaded',initialize);
		function initialize(e) {
			var more, toggle, parent;
			more = $('analysis-opinions-more');
			more.addClassName('with-js');
		
			moreTitle = $('analysis-opinions-more-title');
		
			toggle = document.createElement('a');
			toggle.href = "#";
			toggle.className = 'toggle';
		
			moreTitle.appendChild(toggle);
			Event.observe(moreTitle, 'click', toggleMore);
			toggleMore();
			if (window.getComputedStyle) { // fixes odd Firefox bug that causes parent height to shift
				parent = $('analysis-opinions');
				parent.setStyle({height: window.getComputedStyle(parent, null).getPropertyValue('height')});
			}
			parent = toggle = more = moreUL = false;
			return true;
		}
		function toggleMore(e) {
			if (e) {
				var el = Event.element(e);
				Event.stop(e);
			}
			$('analysis-opinions-more-ul-wrap').toggle();
			return true;
		}
	}(),
	HeadlinesWidget: (function () {
		var AuthenticationEvent = nfl.events.AuthenticationEvent;
		var HomePageEvent       = nfl.events.HomePageEvent;
		var SiteLifeEvent       = nfl.events.SiteLifeEvent;
		var Authentication      = nfl.global.Authentication;
		var ESCAPED_DELIMITER	= /#%7B([^%]+)%7D/g;
		var ClassName = { JS: 'with-js', TOGGLE: 'toggle', CURRENT: 'current' };
		var Headlines = {
			MINE: 'Mine',
			RECOMMENDED: 'Recommended',
			COMMENTED: 'Commented',
			RECENT: 'Recent',
			SIGN_IN: 'SignIn'
		};
		var VIDEO_HTML = ' <span class="showVideoIcon" title="Video"></span>\u00A0'; /*nbsp at the end*/
		var IS_VIDEO   = /^(?:http:\/\/)?[^\/]*\/videos/;


		/**
		 * This is the traffic cop that intercepts the hash changes
		 * to keep state in sync.
		 */
		function onHashChange (e) {
			var section;
			this.form.hide();
			this.toggle.href = getHeadlineLink(Headlines.MINE);
			// Prevents the various AJAX processes from getting confused.
			if ( this.locked ) {
				location.replace(getHeadlineLink(this.currentTab));
				return;
			}

			if ( e && e.memo && e.memo.headlines ) {
				section = e.memo.headlines;
			}
			if ( section === this.currentTab ) { return; }
			switch (section) {
				case Headlines.MINE:
					if ( ! Authentication.isAuthenticated() ) {
						// don't create a history entry
						location.replace(getHeadlineLink(Headlines.SIGN_IN));
						return;
					}
					this.toggle.href = getHeadlineLink(this.currentTab);
					this.showTeamHeadlines(Authentication.getUser().team);
					break;
				case Headlines.RECOMMENDED:
				case Headlines.COMMENTED:
					this.showPluckTab( section );
					break;
				case Headlines.SIGN_IN:
					if ( Authentication.isAuthenticated() ) {
						location.replace(getHeadlineLink(Headlines.SIGN_IN));
						return;
					}
					this.toggle.href = getHeadlineLink(this.currentTab);
					this.form.show();
					return;
				default:
					this.showDefault();
			}
		}
		// Event listeners for the various states
		function onSignIn (e) {
			this.form.hide();
			if ( e.memo.component !== this.ajaxLogin.name ) { return;}
			// Do some fun stuff when it's your sign in
			try {
				setAjaxLoginEvent('event11'); // defined in common_var.js
			}
			catch(e) {
				nfl.log( 'Omniture error: ' + e.message );
			}
		}
		function onAuthFailure (e) {
			this.setFormMessage('Login failed.');
		}
		function onSignOut (e) {
			if ( this.currentTab === Headlines.MINE ) {
				location.replace(getHeadlineLink(Headlines.RECENT));
			}
		}
		function onUnload (e) {
			this.list = this.form = this.toggle = this.navigation = null;
		}
		function onTeamHeadlines (e) {
			var team, content;
			team                   = e.memo.team;
			team.mediumLogoImg     = (team && team.mediumLogo) ? '<img src="' + team.mediumLogo + '" alt="' + team.fullName + ' Team Profile" width="50" height="50" />' : '';
			content                = this.teamTemplate.evaluate(team) + e.memo.newsList.inject('', getAricleHTML, this);
			this.setContent(content, Headlines.MINE);
		}
		function onDiscoveredContent (e) {
			this.setContent(e.memo.DiscoveredContent.inject("", getPluckHTML, this), e.memo.Activity.Name );
		}

		
		// Helper methods
		function getPluckHTML (acc, article) {
			var aHeadline = article.PageTitle.split('||');
			headline = aHeadline[ (aHeadline.length > 1 && (! aHeadline[1].blank())) ? 1 : 0];
			if (IS_VIDEO.test(article.PageUrl)) {
				headline += VIDEO_HTML;
			}
			return getAricleHTML.call(this, acc, { permalink: article.PageUrl, storyHeadline: headline, count: article.count });
		}
		function getAricleHTML (acc, article) {
			return acc + this.template.evaluate(article);
		}
		function getHeadlineLink ( section ) {
			return '#headlines:' + section;
		}
		function templatize(ref) {
			var el, t;
			el = $(ref);
			if (! el) { return; }
			t = new Template(el.innerHTML.replace(ESCAPED_DELIMITER, "#{$1}"));
			el.update('');
			el.hide();
			return t; 
		}
		
		return Class.create({
			initialize: function(options) {
				var mh, toggle;
			
				this.template   = templatize(options.template);
				this.currentTab = Headlines.RECENT;
				this.list       = $(options.list);
				this.recent     = this.list.innerHTML;
				this.locked     = false;
				this.listClassName = this.list.className;

				if ( nfl.news && nfl.news.Comments ) {
					this.mostActivity       = new nfl.news.Comments.MostActivityController({ age: 2 , sections: ['News','Videos'] });
					this.mostActivity.name += '|' + this.name;
					document.observe(SiteLifeEvent.DISCOVERED_CONTENT, onDiscoveredContent.bind(this));
				}
				
				if (options.myHeadlines) {
					mh = $(options.myHeadlines);
					this.myHeadlines = mh.identify();
					mh.addClassName(ClassName.JS);
					this.toggle = mh.select('a.toggle').first();
					this.toggle.show();
					this.form = $(options.form);
					this.form.hide();

					this.ajaxLogin           = new nfl.home.AjaxLoginController( this.form.select('form').first() );
					this.ajaxLogin.name     += '|' + this.name;
					this.teamHeadlines       = new nfl.home.TeamHeadlinesController();
					this.teamHeadlines.name += '|' + this.name;
					this.formMessage         = this.form.select('div.message').first();
					this.teamTemplate = templatize(options.teamTemplate);


					document.observe(AuthenticationEvent.SIGN_IN, onSignIn.bind(this));
					document.observe(AuthenticationEvent.AUTH_FAILURE, onAuthFailure.bind(this));
					document.observe(AuthenticationEvent.SIGN_OUT, onSignOut.bind(this));
					document.observe(HomePageEvent.TEAM_HEADLINES_AVAILABLE, onTeamHeadlines.bind(this));
				}
				if (options.navigation && nfl.news.Comments) {
					this.navigation = $(options.navigation);
					this.navigation.show();
				}
				
				document.observe('window:hashchange', onHashChange.bind(this) );
				Event.observe(window, 'beforeunload', onUnload.bind(this));



				// Get the party started if we've got a hash.
				if (window.location.hash) {
					onHashChange.call(this, { memo: window.location.hashparams.get().toObject() })
				}
			},
			name: 'HeadlinesWidget',
			showPluckTab: function( tab ) {
				this.locked = true;
				// don't cache these because they're supposed to
				// refresh every time. >.<
				this.mostActivity.activities = [ new Activity( tab ) ];
				this.mostActivity.find();
			},
			showTeamHeadlines: function(team) {
				this.locked = true;
				this.teamHeadlines.find(team);
			},
			showDefault: function() {
				this.locked = true;
				this.setContent( this.recent, Headlines.RECENT );
			},
			setFormMessage: function(message, status) {
				this.formMessage.update( (message) ? ('<span class="' + (status || 'error') + '">' + message + '</span>') : '');
			},
			setContent: function( content, tab ) {
				var correctTabRe = new RegExp("#(.*/)?headlines:" + tab + '(/.*)?$');;
				// update the content
				this.list.update( content );
				this.list.className = this.listClassName + ' ' + tab;
				// update navigation
				if ( this.navigation ) {
					this.navigation.select('a').each(function(link) {
						var isCorrectTab = correctTabRe.test(link.href);
						if ( isCorrectTab && ! link.hasClassName(ClassName.CURRENT) ) {
							return link.addClassName(ClassName.CURRENT);
						}
						if ( link.hasClassName(ClassName.CURRENT) && (! isCorrectTab ))  {
							return link.removeClassName(ClassName.CURRENT);
						}
					});
				}
				this.locked = false;
				this.currentTab = tab;
			}

		});
	})(),
	AjaxLoginController: (function () {
		var AJAX_SIGN_IN_URL	= '/ajax/home';
		var AuthenticationEvent = nfl.events.AuthenticationEvent;

		function blankInput(el) { el.value = '';}
		function onLoginSubmit(e) {
			e.stop();
			if ( this.locked ) { return; }
			this.locked = true;
			new Ajax.Request(AJAX_SIGN_IN_URL, {
				method: 'post',
				parameters: 'view=json&' + e.findElement('form').serialize(),
				onSuccess: onLoginSuccess.bind(this),
				onFailure: onLoginFailure.bind(this),
				onComplete: onLoginComplete.bind(this)
			});
		}

		function onLoginSuccess(transport) {
			var json = transport.responseJSON;
			$$('#' + this.form + ' input').each(blankInput);
			document.fire(AuthenticationEvent.SIGN_IN, { component: this.name, username: json.user.username, team: json.user.favoriteTeam });
			document.fire(nfl.events.HomePageEvent.TEAM_HEADLINES_AVAILABLE, { component: this.name, team: json.team, newsList: json.newsList });
		}
		function onLoginFailure(transport) {
			document.fire(AuthenticationEvent.AUTH_FAILURE, { component: this.name });
		}
		function onLoginComplete(transport) {
			this.locked = false;
		}

		return Class.create({
			initialize: function( _ref ) {
				var form = $( _ref );
			
				form.observe('submit', onLoginSubmit.bind(this));
				this.form = form.identify();
			},
			name: 'nfl.home.AjaxLoginController'
		});
	})(),
	TeamHeadlinesController: (function () {
		var TEAM_HEADLINES_URL = '/ajax/members/myHeadlines';
		var EMPTY_TEAM         = { abbr: '' };
		var HomePageEvent      = nfl.events.HomePageEvent;
		var headlines          = new Hash();
		var teams			   = new Hash();

		
		function onAjaxSuccess ( transport ) {
			var json      = transport.responseJSON;
			this.newsList = json.newsList || [];
			this.team     = json.team || EMPTY_TEAM;
			headlines.set( this.team.abbr, this.newsList );
			teams.set( this.team.abbr, this.team );
		}

		function onAjaxFailure ( transport ) {
			this.team     = EMPTY_TEAM;
			this.newsList = [ { headline: 'NFL.com news & headlines', url: '/news' } ];
		}
		function onAjaxComplete (transport) {
			this.locked = false;
			document.fire( HomePageEvent.TEAM_HEADLINES_AVAILABLE, { component: this.name, team: this.team, newsList: this.newsList });
		}
		function onHeadlines (e) {
			var team;
			if ( e.memo.component === this.name ) { return;}
			team = e.memo.team.abbr;
			headlines.set( team, e.memo.newsList );
			teams.set( team, e.memo.team );
		}
		
		return Class.create({
			initialize: function() {
				document.observe( HomePageEvent.TEAM_HEADLINES_AVAILABLE, onHeadlines.bind(this) );
			},
			name: 'nfl.home.TeamHeadlinesController',
			find: function(_team) {
				var team;
				if ( this.locked || (! _team) ) { return; }
				if ( _team === this.team.abbr ) {
					return onAjaxComplete.call(this);
				}
				team = teams.get(_team);
				if ( team ) {
					this.team     = team;
					this.newsList = headlines.get(_team);
					return onAjaxComplete.call(this);
				}
				this.locked = true;
				// Get user headlines
				new Ajax.Request(TEAM_HEADLINES_URL, {
					method: 'get',
					parameters: { team: _team },
					onSuccess: onAjaxSuccess.bind(this),
					onFailure: onAjaxFailure.bind(this),
					onComplete: onAjaxComplete.bind(this)
				});
			},
			team: EMPTY_TEAM,
			newsList: []
		});
	})(),
	ShopImage: Class.create({
		initialize: function(thumbnailDIV, listOL, template) {
			var list, item, items, counter;
			var template, link, li;
			list 		= $(listOL);
			items		= [];
			counter		= -1;
			while (li = list.getElementsByTagName('li')[++counter]) {
				link	= li.getElementsByTagName('a')[0];
				items[counter] = {
					src: li.getElementsByTagName('input')[0].value,
					href: link.href,
					title: (link.innerText || link.textContent)
				};
				link = li = null;
			}
			$(thumbnailDIV).innerHTML = new Template(template).evaluate(items[Math.floor(Math.random() * (items.length))]);
		}
	})
};

