nfl.namespace('live');
nfl.live.VideoGalleryPlayer = Class.create();
nfl.live.VideoGalleryPlayer.prototype = {
	initialize: function(xmlURL, id, adURL, flashVars, parameters) {
		var f;
		this.xmlURL			= xmlURL;
		// In case of emergency, you may set the xmlURL variable manually
		// this.xmlURL = "http://static.nfl.com/static/site/scripts/superbowl/live-c1ontingency.xml";
		this.parentID		= id;
		this.adURL			= adURL;
		this.viewerID		= id + '-viewer';
		this.controllerID	= id + '-controller';
		this.listID			= id + '-list';
		this.carotID		= this.controllerID + '-carot';
		this.firstUpdate	= true;
		f					= (typeof flashVars == 'undefined') ? { emailAFriendBaseUrl: "/email-a-friend?id="} : flashVars
		this.player 		= new nfl.media.video.VideoGalleryPlayer(this.viewerID, adURL, f, parameters);
		this.flashID		= this.player.getFlashID();
		this.updateTime		= 60;
		// createExecutor
		(navigationUpdater = this.updateNavigation())();
		this.executor	= new PeriodicalExecuter(navigationUpdater, this.updateTime);
	},
	playVideo: function() {
		// Function.apply doesn't seem to work for ExternalInterface
		$(this.flashID).playVideo(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4]);
	},
	updateNavigation: function() {
		var listID			= this.listID;
		var parentID		= this.parentID;
		var xmlURL			= this.xmlURL;
		var previous		= "";
		var player			= this.player;
		var firstUpdate		= this.firstUpdate;
		var adURL			= this.adURL;
		var clickHandler	= this.controllerClickHandler();
		var setCarot		= this.getCarotSetter();
		var dieGracefully	= function(transport) {
			var linksUL;
			linksUL		= $(listID);
			if (firstUpdate) {
				player.write();
				Event.observe(linksUL, 'click', clickHandler);
				firstUpdate = false;
			}
			linksUL.innerHTML = "<li class=\"error\">Please stay tuned for NFL.com/Live</li>";
			$$("#" + parentID + " .isStreaming").first().setStyle({display: "none"});
		}
		var processXML		= function(transport) {
			if (previous != transport.responseText) {
				var x, i, controller, item, linksUL, linksHTML, result, customAttrs, isStreaming, streamingEl, progressiveOnly, currentLI, currentID;
				previous 	= transport.responseText;
				x			= transport.responseXML;
				try {
					transport.responseXML.getElementsByTagName('item');
				}
				catch(e) { alert("Won't do it.");}
				linksUL		= $(listID);
				linksHTML	= "";
				// crazy XML mojo to generate links
				isStreaming = false;
				if (firstUpdate) {
					if (item = x.getElementsByTagName('item')[0]) {
						player.setFlashVars({
							id: 			item.getAttribute('id'),
							format:			item.getAttribute('format'),
							mediaFile:		item.getAttribute('mediaFile'),
							mediaPath:		item.getAttribute('mediaPath'),
							previewImage:	item.getAttribute('video_player_cp'),
							dartUrl:		adURL,
							autoplay:		false
						});
					}
					player.write();
					Event.observe(linksUL, 'click', clickHandler);
					firstUpdate = false;
				}
				else {
					currentActive = $A(linksUL.select('.active')).first();
					if (currentActive) { currentID = currentActive.getAttribute('data-id'); }
				}
				i = -1;
				while(item = x.getElementsByTagName('item')[++i]) {
					customAttrs = "";
					['format', 'mediaFile', 'mediaPath', 'video_player_cp', 'id'].each(function(value) { customAttrs+= (" data-" + value + "=\"" + item.getAttribute(value) + "\"") });
					result = "<li title=\"Play this video\" role=\"button\"";
					if (currentID && currentID == item.getAttribute('id')) {
						result += " class=\"active\" aria-checked=\"true\"";
						setCarot(i);
					}
					result+= customAttrs + " onmouseenter=\"$(this).addClassName('hover')\" onmouseleave=\"$(this).removeClassName('hover')\">";
					result+= "<div class=\"thumbnail\"><img src=\"" + item.getAttribute('thumbSmall') + "\" alt=\"\" /></div>";
					result+= "<h3><a href=\"#\" onclick=\"return false\">" + item.getAttribute('body') + "</a> | ";
					if (item.getAttribute('format').match(/stream/i)) {
						result += "<span class=\"live\">Live</span>";
						isStreaming = true;
					}
					else {
						try {
							result += item.getAttribute('runTime').match(/^(00:)?(.*):\d\d$/)[2];
						}
						catch(e){} 
					}
					streamingEl = $$("#" + parentID + " .isStreaming").first();
					progressiveOnly = streamingEl.hasClassName('progressive-only');
					if (isStreaming == progressiveOnly) {
						if (isStreaming) {
							streamingEl.removeClassName('progressive-only');
						}
						else {
							streamingEl.addClassName('progressive-only');
						}
					}
					streamingEl.setStyle({display: "block"});
					result+= " <img src=\"" + nfl.global.imagepath + "/img/superbowl/live/video-link-icon.gif\" alt=\"\" /></h3>";
					result+= "<p>" + (item.getAttribute('caption') || "") + "</p></li>";
					linksHTML += result;
					item = result = customAttrs = null;
				}
				if (linksHTML == "") {
					dieGracefully(transport);
				}
				else { linksUL.innerHTML = linksHTML }
				linksUL = null;
			}
		}
		return function() {
			new Ajax.Request(xmlURL, { onSuccess: processXML, onFailure: dieGracefully, method: "get" })
		}
	},
	controllerClickHandler: function() {
		console.log('controllerClickHandler()');
		var flashID, adURL, timer, timerURL, t, sendTime, currentID;
		flashID		= this.flashID;
		adURL		= this.adURL;
		setCarot	= this.getCarotSetter();
		return function(e) {
			console.log('clickHandler()');
			var li, format, c, s, p, h, carot;
			li = Event.findElement(e, 'li');
			if (li != document && ! (li.hasClassName('active') || li.hasClassName('error'))) {
				format = li.getAttribute('data-format');
				$(flashID).playVideo(
					format,
					li.getAttribute('data-mediaFile'),
					li.getAttribute('data-mediaPath'),
					li.getAttribute('data-video_player_cp'),
					adURL,
					li.getAttribute('data-id')
				);
				i = -1; // element offset
				while (s = li.parentNode.childNodes[++i]) {
					if (s == li) {
						setCarot(i);
						Element.addClassName(s, 'active');
						s.setAttribute('aria-checked', 'true');
					}
					else {
						Element.removeClassName(s, 'active');
						s.setAttribute('aria-checked', 'false');
					}
				}
				li = p = s = carot = null;
				Event.stop(e);
			}
			li = null;
		}
	},
	getCarotSetter: function() {
		var carotID, listID;
		carotID	= this.carotID;
		listID	= this.listID;
		return function(offset) {
			var carot, h;
			carot	= $(carotID);
			h = $$("#" + listID + " li").first().offsetHeight;
			carot.setStyle({ display: 'block', top: (offset * h + (Math.floor(h / 2) - Math.round(carot.offsetHeight / 2))) + "px"});
		}
	}
}
nfl.live.Blog = Class.create();
nfl.live.Blog.prototype = {
	initialize: function(container, src) {
		var e, c;
		e = $(src);
		if (e) {
			// extract url           iframe                   link                      input
			this.url = e.getAttribute('src') || e.getAttribute('href') || e.getAttribute('value');
			e.parentNode.removeChild(e);
		}
		else { this.url = src;}
		if (! this.url) { this.error(src + ' did not contain a valid URL.');}
		c = $(container);
		if (! c) { this.error(container + ' is not a valid container.');}
		else if (c.id) { this.containerID = c.getAttribute('id');}
		else { c.setAttribute(this.containerID = "nfl-live-Blog-container");}  
		this.frequency = 60;
	},
	error: function(s) { throw('Could not create blog: ' + s); },
	stop: function() { this.updater.stop(); },
	start: function(container, url, options) {
		var c, u, f;
		c = container || this.containerID;
		u = url || this.url;
		o = options || { frequency: this.frequency, method: 'get'};
		this.updater = new Ajax.PeriodicalUpdater(c, u, o);
	}
}
/**
 * Checks a Zip code for the proper length and content
 * @namespace nfl.live
 * @class ZipCodeCheck
 *
 * For document-specific implementations, prototype the
 * getValidator method.
 */
nfl.live.ZipCodeCheck = Class.create();
nfl.live.ZipCodeCheck.prototype = {
	initialize: function(input, submit) {
		var i, iID, b, bID, f, fID, c, v, r;
		v = false;
		r = /^\d{5}$/;
		i = $(input);
		b = $(submit);
		f = b.up('form');
		[i, b, f].each(function(el){ if (! el.id) { el.id = "nfl-live-ZipCodeCheck-" + el.nodeName; } });
		bID = b.id;
		iID = i.id;
		fID = f.id;
		c = function(e) {
			$(bID).disabled = (! $(iID).value.match(r));
		};
		Event.observe(i, 'keyup', c);
		Event.observe(i, 'blur', c);
		Event.observe(f, 'submit', function(e) {
			if (! $(iID).value.match(r)) { Event.stop(e);}
		});
		c();
		b = i = f = null;
	}
}

