/* begin MiniStats */
(function($)
{	
	// constructor
	function MiniStats(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_opts = {
				debug: true
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						console.log("str: " + str);
					} 
					catch (e) {
						alert("str: " + str);
					}
				}
			}
		});
	
		// Private methods -----------------------------------------------------------------
	
		function init()
		{	
			var rows = _root.find("table > tbody > tr");
			rows.hover(
				function () {
					$(this).addClass("on");
				}, 
				function () {
					$(this).removeClass("on");
				}

			)
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};

	// jQuery plugin implementation
	$.fn.miniStats = function(conf)
	{
		var opts = {};
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new MiniStats($(this), opts);
		});
		return this; 
	};
})(jQuery);
/* end MiniStats */
(function($)
{	
	// constructor
	function SportsnetPage(conf)
	{	
		// Private fields ------------------------------------------------------------------
		var _self = this,
			_initQueue = [],
			_initObjectUIDCount = 0,
			_tickIntervalID,
			_curInitObject,
			_curState = "paused",
			_rankMap = {
				CORE: 0, //page starters and core functions (e.g., cookie checker); keep in mind - making everything core defeats the purpose :)
				PAGE_MAJOR: 1, //page elements that need to be shown immediately (e.g., top story)
				PAGE_MINOR: 2, //page elements lower on page, or having initial state that shows content (e.g., scrollers, polls)
				NAV: 3, //site navigation (may be counter-intuitive to have under page content, but usually users are here to browse first)
				AJAX: 4,
				DISPLAY: 5 //less noticable display functions that add polish/details (e.g., ellipsis)
			},
			_opts = {
				debug: false
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
		$.extend(_self, {
			registerInit: function(initObj)
			{
				//{_expression:"p", _contextExpression:"#pHolder", _functionRef:"testFunc", _data:{}, _rank:"PAGE_MAJOR"}
				if (initObj._rank == undefined || _rankMap[initObj._rank] == undefined) {
					initObj._rank = "DISPLAY";
				}
				addToQueue(initObj);
			},
			play: function()
			{	
				if (_curState == "paused") {
					_curState = "playing";
					startTicking();
				}
			},
			pause: function()
			{	
				_curState = "paused";
				stopTicking();
			},
			executeInit: function()
			{
				executeNextInit();
			},
			printQueue: function()
			{
				printQueue();
			}
		});
	
		// Private methods -----------------------------------------------------------------
		function initSubQueues()
		{
			//creates a nested array in _initQueue for each of the ranks, at the index associated with the rank
			//e.g., CORE objects array is index 0 in _initQueue
			for (var curRank in _rankMap) {
				_initQueue[_rankMap[curRank]] = [];
			}
		};
		
		function addToQueue(initObj)
		{
			if (objectIsInQueue(initObj) == false) {
				var targetArrayName = initObj._rank;
				var targetArray = _initQueue[_rankMap[targetArrayName]];
				var oldLen = targetArray.length;
				targetArray.push(initObj);
				debug("## addToQueue ADDED item (_expression: " + initObj._expression + "); items in " + targetArrayName + ": " + targetArray.length + " (was " + oldLen + ")");
			} else {
				debug("## addToQueue DID NOT ADD item with _expression: " + initObj._expression + "; item already exists");
			}
		};
		
		function executeInit()
		{
			//always acts on _curInitObject
			//printObjectProps(_curInitObject);
			var funcExists = $.fn[_curInitObject._functionRef] != undefined;
			if (funcExists == true) {
				//the timeout's to make fireFunction() start its own call stack (can't pass params to setTimeout in IE, so arbitrary function it is)
				setTimeout(function(){
					fireFunction(_curInitObject);
				}, 0);
			}
			else {
				debug("## executeInit; DID NOT FIRE; function not found (_functionRef: '" + _curInitObject._functionRef + "')");
				onExecuteInitComplete();
			}
		};
		
		function fireFunction(initObj)
		{
			var start = new Date().getTime();
			var jqParams = [initObj._expression];
			if (initObj._contextExpression != undefined) {
				var contextJQ = $(initObj._contextExpression);
				jqParams.push(contextJQ);
			}
			var jqResultSet = $.apply($, jqParams);
			jqResultSet[initObj._functionRef](initObj._data);
	
			var end = new Date().getTime();
			var timeToExecute = end - start;
			debug("## executeInit>fireFunction (" + _curInitObject._functionRef + "); timeToExecute: " + timeToExecute);
			
			onExecuteInitComplete();
		};
				
		function onExecuteInitComplete()
		{
			//debug("## onExecuteInitComplete; continuing...");
			setTimeout(executeNextInit, 0); //the timeout's to break out of the call stack
		};
		
		function executeNextInit()
		{
			_curInitObject = getNextInitObject();
			if (_curInitObject == undefined) {
				debug("## executeNextInit - no more initObjects available");
			
				postProcessPage();
			}
			else {
				//test to see if context or element is ready (just need to test one, if context exists, element must)
				var jqObj = _curInitObject._contextExpression != undefined ? $(_curInitObject._contextExpression) : $(_curInitObject._expression);
				var jqObj = jqObj != undefined;
				if (jqObj != undefined) {
					executeInit();
				}
				else {
					debug("## executeNextInit; element/context doesn't exist; not executing and continuing...");
					onExecuteInitComplete();
				}
			}
		};
		
		function getNextInitObject()
		{
			var curObj;
			for (var i=0; i<_initQueue.length; i++) {
				var curArray = _initQueue[i];
				curObj = curArray.shift();
				if (curObj != undefined) break;
			}
			return curObj;
		};
		
		function objectIsInQueue(testObj)
		{
			var isInQ = false;
			for (var curRank in _rankMap) {
				var curSubQueue = _initQueue[_rankMap[curRank]];
				for (var i = 0; i < curSubQueue.length; i++) {
					var curIObj = curSubQueue[i];
					var sameExpr = curIObj._expression == testObj._expression;
					var sameContext = curIObj._contextExpression == testObj._contextExpression;
					var sameFunc = curIObj._functionRef == testObj._functionRef;
					var sameData = haveSameData(curIObj, testObj);
					isInQ = sameExpr && sameContext && sameFunc && sameData;
					if (isInQ == true) break;
				}
				if (isInQ == true) break;
			}
			return isInQ;
		};
		
		function haveSameData(testObj1, testObj2){
			//NOTE: this does not recurse - meant for testing primitive values in options object passed to constructor
			var haveSameData = true;
			//if both are null or undefined, we're done
			var obj1HasData = testObj1._data != undefined && testObj1._data != null;
			var obj2HasData = testObj2._data != undefined && testObj2._data != null;
			var bothHaveData = obj1HasData && obj2HasData;
			if (bothHaveData) {
				for (var curProp in testObj1._data) {
					//debug("testing data " + curProp + "; testObj1: " + testObj1._data[curProp] + "; testObj2:" + testObj2._data[curProp]);
					var isMatch = testObj1._data[curProp] == testObj2._data[curProp];
					//debug("isMatch: " + isMatch);
					if (isMatch == false) {
						haveSameData = false;
						break;
					}
				}
			}
			else {
				haveSameData = obj1HasData == obj2HasData;
			}
			return haveSameData;
		};
		
		function printQueue()
		{
			debug("-------------------\nprintQueue...");
			for (var curRank in _rankMap) {
				var curSubQueue = _initQueue[_rankMap[curRank]];
				debug(curRank + " (" + curSubQueue.length + ")");
				for (var i = 0; i < curSubQueue.length; i++) {
					var curIObj = curSubQueue[i];
					debug(" - _expression: " + curIObj._expression + ", _contextExpression: " + curIObj._contextExpression + ", _functionRef: " + curIObj._functionRef + ", _data: " + curIObj._data);
				}
			}
			debug("done\n-------------------");
		};
		
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					trace(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
			
		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);
		};
	
		function postProcessPage()
		{
			//run any functions we need to have happen on page load
			
			//reposition columnist image if necessary
			var copyHolder = $("div.column-page-heaader");
			if (copyHolder.height() > 80) { //magic number - any taller and the image shows space below, AND MUST BE MOVED!
				var titleHolder = $("div.opinion-page-header");
				var imageHolder = $("div.columnist-header-pic");
				var yOffset = $.browser.msie6 ? 0 : 3; //magic number (except for ie6?) - 2 for margin-top, 1 for extra pixel in image cropped by div
				var targetTop = copyHolder.offset().top + copyHolder.height() - imageHolder.height() - yOffset;
				imageHolder.css({
					top: targetTop
				});
			}
		};
	
		function init()
		{
			initSubQueues();
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.sportsnetPage = function(opts)
	{
		return new SportsnetPage(opts);
	};
})(jQuery);

var sportsnetPage =  $.fn.sportsnetPage({});
(function($)
{	
	// constructor
	function TopNavMenu(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_hotspot = _root.parent(),
			_menu,
			_hideTimer,
			_showWait = 150,
			_hideWait = 250,
			_animDur = 150,
			_menuHeight,
			_positionLeft = "default", //hotspot-left 
			_positionTop = "default", //hotspot-top 
			_opts = {
				debug: false
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			toggleMenu: function()
			{
				if (_root.hasClass("on")) {
					_self.debug("calling closeMenu");
					_self.closeMenu();
				}
				else {
					_self.debug("calling doMouseEnter");
					_self.doMouseEnter();
				}
			},
			positionMenu: function()
			{
				if (_menu.hasClass("body-flyout") && _menu.parent()[0].tagName != "BODY") {
					_self.debug("moving menu element to end of document body");
					$("body").append(_menu); //move in-body flyout to end of body (if it's not there already) to avoid messy cascading styles
				}
				
				if (_positionLeft != "default") {
					var targetX;
					switch (_positionLeft) {
						case "hotspot-left":{
							targetX = _hotspot.offset().left;
							break;
						}
						case "hotspot-right":{
							targetY = _hotspot.offset().left + _hotspot.outerWidth();
							break;
						}
					}
					_self.debug("setting left position: " + targetX);
					_menu.css({
						left: targetX
					});
				} else {
					_self.debug("using default _positionLeft");
				}
				if (_positionTop != "default") {
					var targetY;
					switch (_positionTop) {
						case "hotspot-top":{
							targetY = _hotspot.offset().top;
							break;
						}
						case "hotspot-bottom":{
							targetY = _hotspot.offset().top + _hotspot.outerHeight();
							break;
						}
					}
					_self.debug("setting top position: " + targetY);
					_menu.css({
						top: targetY
					});
				} else {
					_self.debug("using default _positionTop");
				}
			},
			openMenu: function()
			{
				if (_root.hasClass("on") == false) {
					_self.debug("openMenu");
					_self.positionMenu();
					_menu.show();
					_menu.animate({height:_menuHeight}, _animDur, "swing", function() { _self.onOpen(); });
				}
			},
			onOpen: function()
			{
				_self.debug("onOpen");
				_root.addClass("on");
			},
			closeMenu: function()
			{
				_self.debug("closeMenu");
				_menu.animate({height:"0px"}, _animDur, "swing", function() { _self.onClose(); });
			},
			onClose: function()
			{
				_self.debug("onClose");
				_menu.hide();
				_root.removeClass("on");
			},
			doMouseEnter: function()
			{
				_self.debug("doMouseEnter");
				clearTimeout(_hideTimer);
				_hideTimer = setTimeout(function(){
					_self.openMenu();
				}, _showWait);
			},
			doMouseLeave: function()
			{
				_self.debug("doMouseLeave");
				clearTimeout(_hideTimer);
				_hideTimer = setTimeout(function(){
					_self.closeMenu();
				}, _hideWait);
			},
			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						trace(str);
					} 
					catch (e) {
						alert("str: " + str);
					}
				}
			}
		});
	
		// Private methods -----------------------------------------------------------------
		
		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);
		};
	
		function init()
		{	
			var hasMenuName = /\bmenu:\s*(\S+)\b/.test(_domElement.className);
			
			_self.debug("_domElement.className: " + _domElement.className);
			_self.debug("hasMenuName: " + hasMenuName);
			
			if (hasMenuName == true) {
				var menuElementName = /\bmenu:\s*(\S+)\b/.exec(_domElement.className)[1];
				_self.debug("menuElementName: " + menuElementName);
				_menu = $("#" + menuElementName);
				
				//by default, just expands the menu in-place; if over-ridden, it positions the menu relative to hotspot
				var hasPositionOverride = /\bposition:\s*(\S+)\b/.test(_domElement.className);
				if (hasPositionOverride == true) {
					var posString = /\bposition:\s*(\S+)\b/.exec(_domElement.className)[1];
					_self.debug("posString: " + posString);
					if (posString.indexOf("left") != -1) {
						_positionLeft = "hotspot-left";
					}
					if (posString.indexOf("top") != -1) {
						_positionTop = "hotspot-top";
					}
					if (posString.indexOf("bottom") != -1) {
						_positionTop = "hotspot-bottom";
					}
				}
			}
			
			if (_menu != undefined) {
				_menuHeight = _menu.height();
				_menu.height("0px");
				
				_hotspot.click(function(){
					_self.toggleMenu();
				});
				_hotspot.mouseenter(function(){
					_self.doMouseEnter();
				});
				_hotspot.mouseleave(function(){
					_self.doMouseLeave();
				});
				_menu.mouseenter(function(){
					_self.doMouseEnter();
				});
				_menu.mouseleave(function(){
					_self.doMouseLeave();
				});
				_menu.find('a').click(function(){
					_self.doMouseLeave();	
				});
			}

		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};

	// jQuery plugin implementation
	$.fn.topNavMenu = function(conf)
	{
		var opts = {};
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new TopNavMenu($(this), opts);
		});
		return this; 
	};
})(jQuery);
/**
 * jquery.scrollable 1.0.4 - Scroll your HTML with eye candy.
 * 
 * ******** With modification for Sportsnet ********
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/scrollable.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Date: 2009-06-08 10:42:59 +0000 (Mon, 08 Jun 2009)
 * Revision: 1898 
 */
(function($) {
		
	// static constructs
	$.tools = $.tools || {version: {}};
	
	$.tools.version.scrollable = '1.0.4';
				
	var current = null;		

	
	// constructor
	function Scrollable(root, conf) {

		// current instance
		var self = this;  
		if (!current) { current = self; }		
		
		// generic binding function
		function bind(name, fn) {
			$(self).bind(name, function(e, args)  {
				if (fn && fn.call(this, args.index) === false && args) {
					args.proceed = false;	
				}	
			});	
			
			return self;
		}
		
		function debug(str) {
			var showDebug = false;
			if (showDebug == true) {
				try {
					console.log(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		}
		
		// bind all callbacks from configuration
		$.each(conf, function(name, fn) {
			if ($.isFunction(fn)) { bind(name, fn); }
		});   
		
		// horizontal flag
		var horizontal = !conf.vertical;				
		
		// wrap (root elements for items)
		var wrap = $(conf.items, root),
			items = wrap.children()
			;
		
		// current index
		var index = 0;		
		
		function find(query, ctx) {
			return query.indexOf("#") != -1 ? $(query).eq(0) : ctx.siblings(query).eq(0);	
		}		
		
		// get handle to navigational elements
		// AlexGorbatchev: replaced find(..., root) with $(root).find(...)
		var navi = $(root).find(conf.navi),
			prev = $(root).find(conf.prev),
			next = $(root).find(conf.next),
			prevPage = $(root).find(conf.prevPage),
			nextPage = $(root).find(conf.nextPage)
			;
		
		// methods
		$.extend(self, {
			
			getIndex: function() {
				return index;	
			},
	
			getConf: function() {
				return conf;	
			},
			
			getSize: function() {
				var size = self.getItems().size();
				
				return conf.fitPages
					? size
					: Math.ceil(size / conf.pageSize) * conf.pageSize
					;
			},
	
			getPageSize: function() {
				return conf.pageSize;
			},
			
			getPageAmount: function() {
				return Math.ceil(this.getSize() / conf.pageSize);
			},
			
			getPageIndex: function() {
				return Math.ceil(index / conf.pageSize);	
			},

			getRoot: function() {
				return root;	
			},
			
			getItemWrap: function() {
				return wrap;	
			},
			
			getItems: function() {
				return items;	
			},
			
			getVisibleItems: function() {
				return self.getItems().slice(index, index + conf.pageSize);	
			},
			
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {
				
				// default speed
				time = time || conf.speed;
				
				// function given as second argument
				if ($.isFunction(time)) {
					fn = time;
					time = conf.speed;
				}
								
				if (i < 0) { i = 0; }				
				if (i > self.getSize() - conf.pageSize) { return self; } 				

				var item = self.getItems().eq(i);					
				if (!item.length) { return self; }				
				
				
				// onBeforeSeek
				var p = {index: i, proceed: true};
				$(self).trigger("onBeforeSeek", p);				
				if (!p.proceed) { return self; }
									
				
				if (horizontal) {
 					var left = -item.position().left;					
					wrap.animate({left: left}, time, conf.easing, fn ? function() { fn.call(self); } : null);
					
				} else {
					var top = -item.position().top;										
					wrap.animate({top: top}, time, conf.easing, fn ? function() { fn.call(self); } : null);							
				}	
				
				
				// navi status update
				if (navi.length) {
					var page = Math.ceil(i / conf.pageSize);
					
					if (conf.maxItemsInNavi > self.getPageAmount()) {
						var klass = conf.activeClass;
						page = Math.min(page, navi.children().length - 1);
						navi.children().removeClass(klass).eq(page).addClass(klass);
					} else {
						$(navi).find(".current").html(page + 1);
					}
				} 
				
				// prev buttons disabled flag
				if (i === 0) {
					prev.add(prevPage).addClass(conf.disabledClass);					
				} else {
					prev.add(prevPage).removeClass(conf.disabledClass);
				}
								
				// next buttons disabled flag
				if (i >= self.getSize() - conf.pageSize) {
					next.add(nextPage).addClass(conf.disabledClass);
				} else {
					next.add(nextPage).removeClass(conf.disabledClass);
				}				
				
				current = self;
				index = i;				
				
				// onSeek after index being updated
				$(self).trigger("onSeek", {index: i});				
				return self; 
			},			
			
				
			move: function(offset, time, fn) {
				var to = index + offset;
				var max = self.getSize() - conf.pageSize;
				
				// AlexGorbatchev: fixed so that looping works in all directions for even and uneven pages
				if (conf.loop == true)
				{
					if (to == self.getSize())
						to = 0;
					else if (to > max)
						to = max;	
					else if (to < 0 && to > - conf.pageSize)
						to = 0;
					else if (to < 0)
						to = max;
				}
				
				return this.seekTo(to, time, fn);
			},
			
			next: function(time, fn) {
				return this.move(conf.scrollByPage ? conf.pageSize : 1, time, fn);	
			},
			
			prev: function(time, fn) {
				return this.move(conf.scrollByPage ? -conf.pageSize : -1, time, fn);	
			},
			
			movePage: function(offset, time, fn) {
				return this.move(conf.pageSize * offset, time, fn);		
			},
			
			setPage: function(page, time, fn) {
				var size = conf.pageSize;
				var index = size * page;
				var lastPage = index + size >= this.getSize(); 
				if (lastPage) {
					index = this.getSize() - conf.pageSize;
				}
				return this.seekTo(index, time, fn);
			},
			
			prevPage: function(time, fn) {
				return this.setPage(this.getPageIndex() - 1, time, fn);
			},  
	
			nextPage: function(time, fn) {
				return this.setPage(this.getPageIndex() + 1, time, fn);
			}, 
			
			begin: function(time, fn) {
				return this.seekTo(0, time, fn);	
			},
			
			end: function(time, fn) {
				return this.seekTo(this.getSize() - conf.pageSize, time, fn);	
			},
			
			reload: function() {
				return load();	
			},
			
			click: function(index, time, fn) {
				
				var item = self.getItems().eq(index);
				var klass = conf.activeClass;			
				
				// check that index is sane
				if (index < 0 || index >= this.getSize()) { return self; }
					
				
				// special case with two items
				if (conf.pageSize == 2) {
					if (index == self.getIndex()) { index--; }
					self.getItems().removeClass(klass);
					item.addClass(klass);					
					return this.seekTo(index, time, fn);
				}
				

				if (!item.hasClass(klass)) {				
					self.getItems().removeClass(klass);
					item.addClass(klass);
					var delta = Math.floor(conf.pageSize / 2);
					var to = index - delta;

					// next to last item must work
					if (to > self.getSize() - conf.pageSize) { 
						to = self.getSize() - conf.pageSize; 
					}
					
					if (to !== index) {
						return this.seekTo(to, time, fn);		
					}				 
				}
				
				return self;
			},

			// callback functions
			onBeforeSeek: function(fn) {
				return bind("onBeforeSeek", fn); 		
			},
			
			onSeek: function(fn) {
				return bind("onSeek", fn); 		
			}			
			
		});
		
		// mousewheel
//		if ($.isFunction($.fn.mousewheel)) { 
//			root.bind("mousewheel.scrollable", function(e, delta)  {
//				// opera goes to opposite direction
//				var step = $.browser.opera ? 1 : -1;
//				
//				self.move(delta > 0 ? step : -step, 50);
//				return false;
//			});
//		}  
		
		// prev button
		prev.addClass(conf.disabledClass).click(function() { 
			self.prev(); 
		});
		
		// next button
		next.click(function() { 
			self.next(); 
		});
		
		// next page button
		nextPage.click(function() { 
			self.nextPage(); 
		});

		// next page button
		prevPage.addClass(conf.disabledClass).click(function() { 
			self.prevPage(); 
		});		

		debug("items.length: " + items.length);
		debug("conf.pageSize: " + conf.pageSize);
		//added test to hide prev/next buttons if there is just one page - Chris Bennett 9/23/09
		var hasMultiplePages = items.length > conf.pageSize;
		if (hasMultiplePages == false) {
			prev.hide();
			next.hide();
			prevPage.hide();
			nextPage.hide();
		}
		
		// keyboard
		if (conf.keyboard) {			

			// keyboard works on one instance at the time. thus we need to unbind first
			$(document).unbind("keydown.scrollable").bind("keydown.scrollable", function(evt) {
				
				var el = current;	
				if (!el || evt.altKey || evt.ctrlKey) { return; }
					
				if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {					
					el.move(evt.keyCode == 37 ? -1 : 1);
					return evt.preventDefault();
				}	
				
				if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
					el.move(evt.keyCode == 38 ? -1 : 1);
					return evt.preventDefault();
				}
				
				return true;
				
			});	 
		}

		// navi 			
		function createDottedNavi() {			
	
			// generate new entries
			if (navi.is(":empty") || navi.data("me") == self) {
				
				navi.empty();
				navi.data("me", self);
				
				for (var i = 0; i < self.getPageAmount(); i++) {		
					
					var item = $("<" + conf.naviItem + "/>").attr("href", i).click(function(e) {							
						var el = $(this);
						el.parent().children().removeClass(conf.activeClass);
						el.addClass(conf.activeClass);
						self.setPage(el.attr("href"));
						return e.preventDefault();
					});
					
					if (i === 0) { item.addClass(conf.activeClass); }
					navi.append(item);					
				}
				
			// assign onClick events to existing entries
			} else {
				
				// find a entries first -> syntaxically correct
				var els = navi.children(); 
				
				els.each(function(i)  {
					var item = $(this);
					item.attr("href", i);
					if (i === 0) { item.addClass(conf.activeClass); }
					
					item.click(function() {
						navi.find("." + conf.activeClass).removeClass(conf.activeClass);
						item.addClass(conf.activeClass);
						self.setPage(item.attr("href"));
					});
					
				});
			}
			
			
			// item.click()
			if (conf.clickable) {
				self.getItems().each(function(index, arg) {
					var el = $(this);
					if (!el.data("set")) {
						el.bind("click.scrollable", function() {
							self.click(index);		
						});
						el.data("set", true);
					}
				});				
			}
			
			
			// hover
			if (conf.hoverClass) {
				self.getItems().hover(function()  {
					$(this).addClass(conf.hoverClass);		
				}, function() {
					$(this).removeClass(conf.hoverClass);	
				});
			}			
			
			return self;
		};
		
		function createNumeredNavi()
		{
			navi.append('<span class="current">1</span>');
			navi.append('<span class="separator">' + conf.numberedNaviSeparator + '</span>');
			navi.append('<span class="total">' + self.getPageAmount() + '</span>');
		};
		
		function createRows()
		{
			var pageSize = conf.size * conf.rows,
				pageCount = Math.ceil(self.getSize() / pageSize)
				;

			for (var i = 0; i < pageCount; i++)
			{
				wrap.find('li').slice(i * pageSize, (i + 1) * pageSize).wrapAll('<div class="scrolling-panel-page"></div>');
			}
		};
		
		if (conf.maxItemsInNavi > self.getPageAmount())
			createDottedNavi();
		else
			createNumeredNavi();
		
		if (conf.rows > 1)
			createRows();
			
		// interval stuff
		var timer = null;

		function setTimer() {
			timer = setInterval(function()  {
					
				// see if interval has been disabled at runtime
				if (conf.interval === 0) { 
					clearInterval(timer); 
				}
				
				self.next();
				
			}, conf.interval);
		}	
		
		if (conf.interval > 0) {			
			
			root.hover(function() {			
				clearInterval(timer);		
			}, function() {		
				setTimer();	
			});
			
			setTimer();	
		}
		
	} 

		
	// jQuery plugin implementation
	// AlexGorbatchev: renamed to scrollingPanel 
	$.fn.scrollingPanel = function(conf) { 

		// AlexGorbatchev: we actually want to be able to recreate the element when called
		// already constructed --> return API
		// var el = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
		// if (el) { return el; }		
		
		var opts = {
			
			// basics
			size: 5,
			scrollByPage: false,			// AlexGorbatchev : allows to scroll in full page sizes
			maxItemsInNavi: 4,				// AlexGorbatchev : converts navi to X/NN style if more pages than this value
			numberedNaviSeparator: ' / ',	// AlexGorbatchev : separator that goes between X and NN when displayed
			vertical: false,			
			clickable: true,
			loop: false,
			interval: 0,			
			speed: 400,
			keyboard: true,			
			
			// other
			activeClass:'active',
			disabledClass: 'disabled',
			hoverClass: null,			
			easing: 'swing',
			
			// navigational elements
			items: '.items',
			prev: '.prev',
			next: '.next',
			prevPage: '.prevPage',
			nextPage: '.nextPage',			
			navi: '.navi',
			naviItem: 'a',
			api: false,
			
			// callbacks
			onBeforeSeek: null,
			onSeek: null
			
		};
		
		
		// AlexGorbatchev: default sportsnet values
		$.extend(opts, {
			scrollByPage: true,
			rows: 1,
			items: 'ul',
			hoverClass: 'hover',
			next: '.navigation .next', 
			prev: '.navigation .prev',
			navi: '.navigation .pager',
			fitPages: false,
			loop: false,
			keyboard: false
		});
		
		$.extend(opts, conf);	
		
		// allows specifying size like '3x2'
		if (typeof(opts.size) == 'string' && /^\d+x\d+$/.test(opts.size))
		{
			var $parts = opts.size.split('x');
			opts.size = parseInt($parts[0]);
			opts.rows = parseInt($parts[1]);
		}
		
		opts.pageSize = opts.size * opts.rows;
		
		this.each(function()
		{
			el = new Scrollable($(this), opts);
			$(this).data("scrollable", el);	
		});
		
		return opts.api ? el: this; 
		
	};
			
	
})(jQuery);
(function($)
{	
	// constructor
	function MediaAndPhotos(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_self = this,
			_mediaPanel = _root.find(".scrolling-panel.media"),
			_mediaPanelHtml
			;
	
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			activateMediaSection: function(index)
			{
				var $url = conf.mediaSections[index][1],
					$aTags = _root.find('.header .sections a')
					;
				
				$aTags.removeClass('active')
				$($aTags[index]).addClass('active');
				
				_self.loadMedia($url);
			},
			
			loadMedia: function(url)
			{	
				var $minTimePassed = false,
					$timer = getTimer(),
					$minTime = 500
					;

				_mediaPanel.find('.loading').show();
				
				function process(json)
				{
					_mediaPanel.html(_mediaPanelHtml);
					_mediaPanel.find('.loading').hide();
					
					var $items = $(_self).triggerHandler("mediaLoaded", [ json ]),
						$container = _mediaPanel.find(".scroll-container"),
						$ul
						;
					
					$container.html('<ul></ul>');
					$ul = $container.find("ul");
					
					for (var $i = 0; $i < $items.length; $i++) 
					{
						var $item = $items[$i];
						
						$(
						'<li>'
							+ '<div class="text"><div class="ellipsis">' + $item.label + '</div></div>'
							+ '<div class="img" style="background-image: url(' + $item.thumb + ')" />'
							+ '<span class="video"><img src="/assets/img/top_story/btn_play.png" /></span>'
						+ '</li>'
						).appendTo($ul);
						
						$ul.find('li:last')
							.data('url', $item.url)
							.click(function()
							{
								window.location = $(this).data('url');
							});
					}

					_mediaPanel.scrollingPanel($.extend({ size: '3x2' }, conf));
					
					$ul.find('.text > .ellipsis').ellipsis();
				};
				
				$.ajax({
					type: "GET",
					url: url,
					dataType: "json",
					success: function(json){
						var $time = getTimer() - $timer;
						
						if ($time > $minTime) 
							process(json);
						else 
							setTimeout(function(){
								process(json);
							}, $minTime - $time);
					}//,
					//error: function(XMLHttpRequest, textStatus, errorThrown){
						// typically only one of textStatus or errorThrown will have info
					//	trace("textStatus: " + textStatus);
					//	trace("errorThrown: " + errorThrown);
					//}
				});
			},
			
			createItem: function(url, thumb, label)
			{
				return { url : url, thumb : thumb, label : label };
			}
		});
	
		// Private methods -----------------------------------------------------------------
		
		function getTimer()
		{
			return new Date().getTime();
		};
		
		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);	
		};
	
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
				
			var $photosPanel = _root.find(".scrolling-panel.photos");
			
			$photosPanel.scrollingPanel($.extend({ size: 1 }, conf));
			$photosPanel.find('li div p').addClass('ellipsis multiline').ellipsis();
			$photosPanel.find('li').click(function()
			{
				window.location = $(this).find('a')[0].href;
			})		
			
			var $sectionLinksContainer = _root.find(".header .sections"),
				$sections = []
				;
			
			//only show the section links if there's more than one section
			if (conf.mediaSections.length > 1) {
				for (var $i = 0; $i < conf.mediaSections.length; $i++) {
					var $item = conf.mediaSections[$i], $text = $item[0];
					
					$('<a href="#">' + $text + '</a>').appendTo($sectionLinksContainer);
					$('<span>|</span>').appendTo($sectionLinksContainer);
					
					$sectionLinksContainer.find('a:last').data('sectionIndex', $i).click(function(){
						_self.activateMediaSection($(this).data('sectionIndex'));
						return false;
					});
				}
			}
			
			// remove the last extra divider
			$sectionLinksContainer.find("span:last").remove();

			// add loader to the media panel
			_mediaPanel.append('<div class="loading">Loading</div>');

			// keep html those far
			_mediaPanelHtml = _mediaPanel.html();

			_mediaPanel.find('.loading').hide();
			
			// activate default first section
			_self.activateMediaSection(0);
		};
	
		// Initialization ------------------------------------------------------------------
		
		// bind all callbacks from configuration
		$.each(conf, bind);
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.mediaAndPhotos = function(conf)
	{ 
		var opts = {
			scrollByPage: true,
			items: 'ul',   
			hoverClass: 'hover',
			next: '.navigation .next', 
			prev: '.navigation .prev',
			navi: '.navigation .pager',
			keyboard: false
		}; 
		
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new MediaAndPhotos($(this), opts);
			$(this).data("mediaAndPhotos", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function TopModule(root, conf)
	{	
		// Private fields -------------------------------------------------------------------

		var _root = $(root),
			_ul = _root.find('> ul'),
			_thumbsHolder = _root.find('> ul.main'),
			_thumbs = _thumbsHolder.find('div.image-clip img'),
			_thumbBtns,
			_container = _root.find('.top-story-container'),
			_brightcovePlayer,
			_brightcovePlayerNameRoot = 'TopStoryPlayer',
			_curBrightcovePlayerName,  //_brightcovePlayerNameRoot appended with random number on each create to eliminate issues with IE (multiple audio streams were playing when user clicked a new thumbnail in the top story module)
			_closeBtnHtml = '<div id="videoClose">close</div>',
			
			_self = this,
			_timer = 0,
			_itemCount = _ul.children().length,
			_itemIndex = 0,
			
			_canToggleOverlay = true,
			_overlayDelay = 0,
			_expendClass = 'expanded';
			_opts = {
				debug: false
			}
			;
			
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			next: function() 
			{
				_itemIndex ++;
				
				if (_itemIndex >= _itemCount)
					_itemIndex = 0;
					
				this.activate(_itemIndex);
			},
			
			activate: function(index)
			{
				var $curActive = _container.find('.content.active');

				if ($curActive.hasClass('video') == true)
				{
					$curActive.find('> a').show();
					removeBrightcove();
				}
				
				conf.hideFunc($curActive.removeClass('active'));
				conf.showFunc(_container.find('.content:eq(' + index + ')').addClass('active'));

				_ul.find('li').removeClass('active');
				
				_ul.find('li:eq(' + index + ')').addClass('active');
				
				$curActive = _container.find('.content.active');
				if ($curActive.hasClass('video') == false)
				{
					positionTextFields();
				}
				
				updateOverlay($curActive);
				
				return $curActive;
			},
			
			initCloseButton: function(){
				_container.find(".video.active").prepend(_closeBtnHtml);
				$("#videoClose").click(function(){
					_self.closeVideo();
				});
			},
			
			clearCloseButton: function(){
				$("#videoClose").remove();
			},
			
			closeVideo: function(){
				_container.find('.content.active a').show();
				removeBrightcove();
				setTimer();
			},
			
			playVideo: function(a)
			{	
				//_self.initCloseButton();
				_container.addClass("video-playing");
				_thumbs.hide();
				_thumbBtns.hide();

				var $videoId = $(a).attr('href').replace('#', ''),
					$container = $(a)[0].parentNode
					;

				// replace content of the parent node with SWF
				$(a).hide();
				createBrightcove($container, $videoId);

				// not forgetting to stop the timer
				stopTimer();
			}
		});

		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					console.log(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};

		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn))
				$(_self).bind(name, fn);
		};
				
		function setTimer()
		{
			clearInterval(_timer);
			_timer = setInterval(function()
			{
				// see if interval has been disabled at runtime
				if (conf.interval == 0) 
					stopTimer(); 

				_self.next();
			}, conf.interval);
		};
		
		function stopTimer()
		{
			if (_timer == 0)
				return;
				
			clearInterval(_timer);
			_timer = 0;
		};

		// positionTextFields added by Gord 24/06/09
		function positionTextFields()
		{
			var $curContent = _container.find('.content.active'),
				$totalHeight = $curContent.height(),
				$curSummary = $curContent.find('.top-story-summary'),
				$curColumn = $curSummary.parent(),
				$headerHeight;

				
			if ($curContent.hasClass('five-cols')) {
				$headerHeight = $curContent.find('h3').outerHeight();
			}	else {
				$headerHeight = 0;
			}

			var	$staticHeight = $curColumn.outerHeight() - $curSummary.outerHeight() + $headerHeight;
				$lineHeight = Math.ceil(($curSummary.css('line-height').split('p'))[0]),
				$numRows = Math.floor(($totalHeight - $staticHeight) / $lineHeight),
				$summaryHeight = $numRows * $lineHeight
				;

			if ($curSummary.height() > $summaryHeight) {
				$curSummary.height($summaryHeight);
			}
		};
		
		function animateOverlay(expandable, targetAttribute, targetValue)
		{
			var $animationArgs = {};
			
			_canToggleOverlay = false;
			
			$animationArgs[targetAttribute] = targetValue;
			
			expandable.animate($animationArgs, { queue : false, duration : 150, complete: function()
			{
				_canToggleOverlay = true;

			}});
			
			stopTimer();
		};
		
		function resetOverlay(expandable, targetAttribute, targetValue)
		{
			expandable.css(targetAttribute, targetValue);
		};

		function toggleOverlay(expandable, expand, callback)
		{
			if (_canToggleOverlay == false)
				return;
				
			var $overlay = expandable.find('.overlay'),
				$container = expandable.parent('.content.five-cols'),
				$position = /\bposition-(\w+)-(\w+)\b/.exec(expandable[0].className),
				$verticalPosition = $position[1],
				$horizontalPosition = $position[2],
				$targetValue = expand ? 0 : $container.height() - expandable.data('__height'),
				$targetAttribute = { 'bottom' : 'top', 'top' : 'bottom' }[$verticalPosition]
				;
			
			expandable[(expand ? 'add' : 'remove') + 'Class'](_expendClass);
			callback(expandable, $targetAttribute, $targetValue);
			
			// for IE6 we have to also expand hight because it seems that bottom:0
			// isn't really sticking.
			if ($.browser.msie6)
			{
				var $container = expandable.parent('.content.five-cols');
				callback(
					expandable, 
					'height', 
					(expand ? $container.height() : expandable.data('__height')) - 2 // 2 pixels extra in IE6... not sure why
					);
			}

		};
		
		function updateOverlay(content)
		{
			$(content).find('.overlay.expandable').each(function()
			{
				var $expandable = $(this);

				if ($expandable.data('__height') != null)
					return;

				$expandable
					.data('__height', $expandable.height())
					//.mouseleave(close).mouseenter(open)
					//.find('h3')
						//.click(toggle)
					;
				$expandable
					.find('a.expand').click(toggle);

				function open()
				{
					toggleOverlay($expandable, true, animateOverlay);
					$expandable.data('toggle', closeNow);

					clearTimeout(_overlayDelay);
					_overlayDelay = 0;
					return false;
				};

				function closeNow()
				{
					toggleOverlay($expandable, false, animateOverlay);
					$expandable.data('toggle', open);
					_overlayDelay = 0;
					return false;
				};

				function close()
				{
					clearTimeout(_overlayDelay);
					_overlayDelay = setTimeout(closeNow, 250);
					return false;
				};

				function toggle()
				{
					toggleOverlay($expandable, !$expandable.hasClass(_expendClass), animateOverlay);
					//$expandable.data('toggle')();
					return false;
				};
				
				// reset initial coordinates so that animation works fine in most browsers
				toggleOverlay($expandable, true /*false /* keep closed */, resetOverlay);
			});
		};
		
		function initLayout()
		{
			// generate layout -----------------------------------------

			
			_ul.find('li.thumb').each(function(index)
			{
				_this = $(this);
				
				if (_this.find('.content').hasClass('video')) {
					_this.find('span.video').show();
				}
				
				_this.click(function()
				{
					var $content = _self.activate(index);
					
//					if ($content.hasClass('video'))
//						_self.playVideo($content.find('> a'));
					
					stopTimer();
					return false;
				});
				_this.show();
			});
			
			// move all content to the container
			_ul.find('li .content').appendTo(_container);
			
			_container.find('.content').hide();
			
			// activate first container
			_self.activate(_itemIndex);
			
			// hide the list if there's just one item
			if (_itemCount <= 1)
				_ul.hide();
			
			// set up image to swf functionality ------------------------
			
			_container.find('.content.video a').click(function()
			{
				_self.playVideo(this);
				return false;
			});
			
			_ul.find('.top-story-caption').ellipsis();
			
			_root.bind('onMediaComplete', function(e){
				setTimer();
			});
			
			_thumbBtns = _thumbsHolder.find('span.video:visible');
		};

		function createBrightcove(container, videoId)
		{
			var $params = {
					playerID : "53059221001",
					videoId : videoId,
					autoStart : "true",
					bgcolor : "#000000",
					wmode : "opaque",
					width : "645",
					height : "416", /* 350px for 4:3; 416px for 16:9 */
					isVid : "true",
					isUI : "true",
					cacheAMFURL : "http://services.brightcove.com/services/messagebroker/amf"
				};
			
			_brightcovePlayer = brightcove.createElement("object");
			_curBrightcovePlayerName = _brightcovePlayerNameRoot + (Math.round(Math.random() * 10000));
			_brightcovePlayer.id = _curBrightcovePlayerName;

			for (var $key in $params)
			{
			     $parameter = brightcove.createElement("param");
			     $parameter.name = $key;
			     $parameter.value = $params[$key];
			     _brightcovePlayer.appendChild($parameter);
			}

			brightcove.createExperience(_brightcovePlayer, container, true);
			
			debug("created brightcove player: " + _curBrightcovePlayerName);
		};
		
		function removeBrightcove()
		{
			if (_brightcovePlayer != null)
			{
				debug("removing brightcove player: " + _curBrightcovePlayerName);
				//_self.clearCloseButton();
				var curExp = brightcove.getExperience(_curBrightcovePlayerName);
				var curPlayer = curExp.getModule(APIModules.VIDEO_PLAYER);
				curPlayer.mute(); //this is to address the "ghost multi-streams" that were playing in IE only
				
				brightcove.removeExperience(_curBrightcovePlayerName);
				_brightcovePlayer = null;
				_container.removeClass("video-playing");
				_thumbs.show();
				_thumbBtns.show();
			}
		};
		// Initialization ------------------------------------------------------------------
		
		// bind all callbacks from configuration
		$.each(conf, bind);
		
		initLayout();
		
		if (conf.interval > 0 && _itemCount > 1) 
		{
			setTimer();	
		}
	};

	// jQuery plugin implementation
	$.fn.topModule = function(conf)
	{ 
		var opts = {
			interval : 5000,		// Number of miliseconds to for auto rotation. 0 - no auto rotation
			hideFunc : function(element) { element.hide(); },
			showFunc : function(element) { element.fadeIn(); }
		}; 
		
		$.extend(opts, conf);
		
		this.each(function() 
		{
			var $instance = new TopModule($(this), opts);
			$(this).data("topModule", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function Poll(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_userHasVoted,
			_resultContainer = _root.find('#poll-result-container'),
			_answerElem = _root.find('.poll-answers'),
			_opts = {
				debug: false
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
//		$.extend(_self, {
//		});
	
		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					console.log(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
			
		// generic binding function
		
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);
		};
		
		function showPollAnswers()
		{
			_resultContainer.hide();
			_answerElem.show();
		};
		
		function showPollResults(submitAnswer){
			//submitAnswer is false if the user clicks the "view results" link
			
            // make ajax request to vote and retrieve results
            var response_id = _answerElem.find('input[name=poll]:checked').val();
            if (!response_id || submitAnswer == false) response_id = '';
			debug("response_id: " + response_id);

            $.ajax({
                url: "/scrum/poll_vote.php",
                cache: false,
                data: "poll_id="+_opts.poll_id+"&response_id="+response_id,
                success: function(html) {
					_answerElem.hide();
                  // update poll-results
					_resultContainer.html(html);
					_resultContainer.fadeIn();
					_userHasVoted = getVoteStatus();
					debug("aft _userHasVoted: " + _userHasVoted);
					if (_userHasVoted == false) showAnswersLink();
                }
            });
			
			return false;
		};
		
		function showAnswersLink(){
			var linkHtml = '<div class="arrow" style="margin:7px 0 0 10px;"><a href="#" id="pollVoteNowLink">Vote Now</a></div>';
			_resultContainer.append(linkHtml);
			_root.find("#pollVoteNowLink").click(function(){
				showPollAnswers();
				return false;
			});
		};
		
		function enableButton(){
			$("#pollVoteButton", _root).removeClass("buttonInactive");
			$("#pollVoteButton", _root).click(showPollResults);
		};
		
		function getVoteStatus(){
			var hasVoted = false;
			
            var polls = $.cookie('polls');
            if (polls) {
				var pollsVoted = polls.split('|');
			
                $.each(pollsVoted, function(key, value) {
                    if (value == _opts.poll_id) {
						hasVoted = true;
					}
                });
            }
			return hasVoted;
		};
	
		function init()
		{
            // see if user has already voted
			_userHasVoted = getVoteStatus();
			
			debug("_userHasVoted: " + _userHasVoted);
			
            if (_userHasVoted == true) {
                showPollResults();
            } else {
                _answerElem.find("input").click(enableButton);
                $("#pollShowResultsLink", _root).click(function(){
					showPollResults(false);
					return false;
				});
                showPollAnswers();
            }
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.poll = function(conf)
	{
		var opts = { };
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new Poll($(this), opts);
		});
		
		return this;
	};
})(jQuery);
(function($)
{	
	// constructor
	function UserInfoModule(root)
	{	
		// Private fields -------------------------------------------------------------------

		var _root = $('body'),
			_signIn = $('.sign-in-link'),
			_signInCancel = $('#sign-in-cancel'),
			_login = $('#login-btn'),
			_channelSelector = $('#channel-selector'),
			_channelWrapper = $('.channel-wrapper'),
			_channelTip = $('.channel-tip'),
			_channelChoicesToggle = $('.channel-choices-toggle'),
			_channelOptions = $('.channel-option'),
			_logout = $('#logout-link'),
			_settings = $('#settings-link'),
			_userName = $('#user-name'),
			_passwordLabel = _root.find('#password-label'),
			_password = _root.find('#password'),
			_overlayBlocker = _root.find('.overlay-blocker'),
			//_overlayChannelSelector = _root.find('.overlay-channel-selector'),
			//_overlayChannelButtons = $(_root.find('#channel-buttons')).find('a'),
			//_overlayChannelInfo = _root.find('#channel-info'),
			_userChannel = "Ontario",
			_leftChannelBar = _root.find('.region'),
			_self = this,
			_opts = {
				debug: false
			}

			;  

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			
			//check for channel cookie
			doCookieCheck: function (whichCookie)
			{
				var $myCookie = whichCookie;
				var c = $.cookies.get($myCookie);
				_self.debug("doCookieCheck for '"+whichCookie+"'; value: " + c);
				
				if (c != null) {
					_userChannel = c;
					$.cookies.del($myCookie);
					_self.doCookieSet($myCookie, c);
					return true;
				} else {
					//alert("doCookieCheck: cookie: "+c);
					return false;
				}
			},	
			
			//set user's channel cookie
			doCookieSet: function (whichCookie, whichValue)
			{
				var $tmp = window.location.href,
					$url = $tmp.split('/'),
					$loc = $url[2].split('.'),
					$dom = '.'+$loc[1]+'.'+$loc[2];
				 var cookieOptions = {
				    path: '/',
					domain: $dom,//'.pairsite.com', //'.sportsnet.ca',
				    hoursToLive: 90000,
				    secure: false
				  }
				var $cookie = whichCookie;
				var $value = whichValue;
				$.cookies.set($cookie, $value, cookieOptions);

			},
			
			//open channel selection overlay
			doChannelSelectOverlay: function () 
			{
				var $blockerHeight = $('body').height();
				
				//var $topnavXOffset = 6; //distance from _overlayChannelSelector to edge of top nav.
				var $rightEdge = _channelWrapper.offset().left +  _channelWrapper.outerWidth(); //+ $topnavXOffset;
				var $targetX = $rightEdge - _overlayChannelSelector.outerWidth();
				var $logoYOffset = 37;
				var $targetY = _channelWrapper.offset().top - $logoYOffset;


				_overlayChannelSelector.css({left: $targetX, top: $targetY});
				_overlayChannelSelector.fadeIn('slow');

				if ($blockerHeight > _overlayBlocker.height()) {
					_overlayBlocker.css({
						height: $blockerHeight
					});
				}
				_overlayBlocker.toggleClass('hidden');

			},
			
			//close channel selection overlay and set cookie from user input
			closeOverlay: function () 
			{
				_self.doCookieSet('sn_region', _userChannel);
				var content = _overlayChannelSelector.find('#select-content');
				var header = _overlayChannelSelector.find('#select-header');
				header.fadeOut('fast');
				content.children().slideUp('fast');
				content.animate({
					height: '0px',
					width: '200px',
					left: '770px',
					right: '1080px'}, 400, function() { _self.reloadPage(); });
			},
			//refresh page - used when user changes the channel choice.
			reloadPage: function () 
			{
				_overlayBlocker.slideUp();
				location.reload();
			},
			
			//set the text for the current channel.
			initUserChannel: function ()
			{
				var $klass = _userChannel.toLowerCase();
				$('#cur-channel').removeClass();
				$('#cur-channel').addClass($klass);
				$($('#channel-options').find('.'+$klass)).addClass('on');
				$('#cur-channel').text(_userChannel);
				
				_leftChannelBar.find('.on').removeClass('on');
				_leftChannelBar.find('#reg-'+_userChannel).addClass('on');
				_leftChannelBar.slideDown();
			},
			
			//show the user sign in form.
			showLogin: function()
			{
				$('.welcome').fadeOut('fast');
				$('.channel-wrapper').fadeOut('fast');
				$('.sign-in').fadeIn();
			},
			
			//submit sign-in info - TODO validation.
			doSignIn: function() 
			{
				$('.sign-in').fadeOut('fast');
				$('#user-display-name').text($('#user-name').val());
				$('.logged-in').fadeIn();
				$('.channel-wrapper').fadeIn();
			},
			
			//toggles the channel selection drop down.
			doOpenChannelSelect: function() 
			{
				$('.channel-choices-toggle').addClass('close');
				_channelWrapper.addClass('active');
			},
			doCloseChannelSelect: function() 
			{
				$('.channel-choices-toggle').removeClass('close');
				_channelWrapper.removeClass('active');
			},
			
			//cancels login and takes user back to greeting message.
			cancelSignIn: function() 
			{
				$('.sign-in').fadeOut('fast');
				$('.welcome').fadeIn();
				$('.channel-wrapper').fadeIn();
			},
			
			//user logs out and is returned to greeting message.
			doLogout: function() 
			{
				$('.logged-in').fadeOut('fast');
				$('.welcome').fadeIn();
			},
			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						console.log("str: " + str);
					} 
					catch (e) {
						//alert("str: " + str);
					}
				}
			}
		});

		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	
			//_root.append(_overlayBlocker);
			//_root.append(_overlayChannelSelector);
			
			var _cookieCheck = _self.doCookieCheck('sn_region');
			
			if (_cookieCheck == false){
				// remove the bottom lines to disable regional selection
				//_leftChannelBar.hide('fast');
				//_self.doChannelSelectOverlay();
			} else {
				_self.initUserChannel();
			};
			
			_signIn.click(function(){
				_self.showLogin();
			}),
			
			_login.click(function() {
				_self.doSignIn();
			}),
			
			_signInCancel.click(function() {
				_self.cancelSignIn();
			}),
			_userName.focus(function() {
				_userName.val('');
			}),	
			_userName.blur(function() {
				if(_userName.val() == ''){
					_userName.val('Username');
				}
			}),
			_passwordLabel.focus(function(){
				_passwordLabel.addClass('hidden');
				_password.removeClass('hidden');
				_password.focus();
			}),
			_password.blur(function(){
				if(_password.val() == "") {
					_password.addClass('hidden');
					_passwordLabel.removeClass('hidden');
				}
			}),

			//_channelTip.hoverIntent(_self.doShowTip, _self.doHideTip); 
			
			_channelOptions.click(function() {
				
				if ($(this).hasClass('on') == false) {
					var txt = this.innerHTML;
					var $color = $(this).css('color');
					
					$('#cur-channel').text(this.innerHTML);
					$('#cur-channel').css({
						color: $color
					});
					
					_userChannel = txt;
					_self.doCookieSet('sn_region', _userChannel);
					for (var i = 0; i < _channelOptions.length; i++) {
						var curOption = _channelOptions.eq(i);
						if (curOption.text() == this.innerHTML) {
							curOption.addClass('active');
						}
						else {
							curOption.removeClass('active');
						}
					}
					_self.doCloseChannelSelect();
					_self.reloadPage();
				}	
			}),
			
			_channelChoicesToggle.click(function() {
				if(_channelChoicesToggle.hasClass('close') == true) {
					_self.doCloseChannelSelect();
				} else {
					_self.doOpenChannelSelect();
				}
			}),

			_channelWrapper.hoverIntent(function()	{ 
  				//do nothing
 
 			}, function() {	
				if(_channelWrapper.hasClass('active') == true) {
					_self.doCloseChannelSelect();
				}
			}),	
			
			_logout.click(function() {
				_self.doLogout();
			}),
			/*
			_overlayChannelButtons.click(function(evt) {
				var id = $(this).attr('id');
				var str = id.split('-');
				var ch = str[1];
				_userChannel = ch;
				_self.closeOverlay()
			}),
			
			_overlayChannelButtons.hoverIntent(function () {
				var id = $(this).attr('id');
				var str = id.split('-');
				var ch = str[1];
				var info = _overlayChannelInfo.find('#info-'+ch);
				info.fadeIn('fast');
			}, function() {
				var id = $(this).attr('id');
				var str = id.split('-');
				var ch = str[1];
				var info = _overlayChannelInfo.find('#info-'+ch);
				info.fadeOut('fast');
			}),
			*/
			_leftChannelBar.find('a').each(function(){
				$(this).click(function() {
					if ($(this).hasClass('on') == false) {
						var id = $(this).attr('id');
						var str = id.split('-');
						var ch = str[1];
						_userChannel = ch;
						_self.doCookieSet('sn_region', _userChannel);
						_self.reloadPage();
					}
				});
			})
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.userInfoModule = function()
	{ 
		this.each(function() 
		{
			var $instance = new UserInfoModule($(this));
			$(this).data("userInfoModule", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function GameDay(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_self = this,
			_isStacked = _root.hasClass("stacked"),
			_gamesCount = _root.find(".game").length,
			_container = _root.find('.game-day-container'),
			_footer = _root.find('.game-day-footer'),
			_currentGameIndex = 0,
			_fullHeight,
			_stackedHeight,
			_prevA,
			_nextA,
			_toggleA
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			showGame: function(index, dontAnimate)
			{
				var $old = _root.find(".game.active"),
					$new = _root.find(".game:eq(" + index + ")").addClass("active")
					;
					
				if (dontAnimate != true)
				{
					conf.hideFunc($old);
					conf.showFunc($new);
				}
				else
				{
					$old.hide();
					$new.show();
				}

				updateSportFromGame($new[0]);
				updateFooterFromGame($new[0]);
				
				// ellipsis can only be applied to visible elements
				if ($new.data('eli') != true)
				{
					$new.find('.details .link-list a:only-child')
						.addClass('ellipsis')
						.ellipsis()
						;
					$new.data('eli', true);
				}
			},
			
			nextGame: function()
			{
				if (_currentGameIndex + 1 < _gamesCount)
				{
					_self.showGame(++_currentGameIndex);
					updatePrevNextButtons();
				}
				
				return false;
			},
			
			prevGame: function()
			{
				if (_currentGameIndex - 1 >= 0)
				{
					_self.showGame(--_currentGameIndex);
					updatePrevNextButtons();
				}

				return false;
			},
			
			toggleGame: function()
			{
				var $game = $(this).parents('.game');

				// apply ellipsis to all items here
				if ($game.data('eli') != true)
				{
					$game.find('.details .link-list a:only-child')
						.addClass('ellipsis')
						.ellipsis()
						;
					$game.data('eli', true);
				}

				updateSportFromGame($game[0]);
				updateFooterFromGame($game[0]);
				
				if ($game.hasClass('closed'))
				{
					_root.find('.game:not(.closed)').height(_stackedHeight).addClass('closed');
					$game.height(_fullHeight).removeClass('closed');
				}
				else
				{
					$game.height(_stackedHeight);
					$game.addClass('closed');
					_footer.find('.footer-message').hide();
				}

				stackGames();

				return false;
			}
		});
	
		// Private methods -----------------------------------------------------------------
		
		function updateSportFromGame(game)
		{
			var $sport = /sport-(\w+)/.exec(game.className)[0];
			var $newClass = 'sport-image ' + $sport;
			var $image = _root.find('.sport-image')[0];
			
			if ($image.className != $newClass)
			{
				$($image).hide();
				$image.className = $newClass;
				$($image).fadeIn('slow');
			}
		};
		
		function updateFooterFromGame(game)
		{
			var $class = '.footer-message';
			var $msg = $(game).find($class);
			var $html = $msg.html();
			var $footer = _footer.find($class);
			
			if ($html != null && $html != '' && !_isStacked)
			{
				$footer.show();
				$footer.html($html);
			}
			else
			{
				$footer.hide();
			}
		}
		
		function updatePrevNextButtons()
		{
			var $disabled = "disabled";
			
			_root.find(".buttons a").removeClass($disabled);
			
			if (_currentGameIndex == 0)
				_prevA.addClass($disabled);

			if (_currentGameIndex + 1 >= _gamesCount)
				_nextA.addClass($disabled);
		};
		
		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);	
		};
	
		function stackGames()
		{
			var top = 0;
			
			_root.find('.game').each(function()
			{
				$(this).css('top', top);
				top += $(this).height();
			});
			
			_footer.css('top', top + _container[0].offsetTop);
			_root.css('height', _footer[0].offsetTop + _footer.height());
		}
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
			
			if (_isStacked == false)
			{
				_root.find(".game").hide();
				
				$('<div class="buttons">'
					+ '<a href="#" class="prev"></a> '
					+ '<a href="#" class="next"></a>'
				+ '</div>').appendTo(_root);
			}
			else
			{
				_fullHeight = _root.find('.game').height()
				_root.find(".game").addClass('stacked closed');
				_stackedHeight = _root.find('.game.stacked').height()

				$('<div class="buttons">'
					+ '<a href="#" class="toggle"></a> '
				+ '</div>').appendTo(_root.find('.game'));
				
				stackGames();
			}
				
			_self.showGame(0, true /* don't animate */);
			
			_prevA = _root.find(".buttons a.prev");
			_nextA = _root.find(".buttons a.next");
			_toggleA = _root.find(".buttons a.toggle");
			
			_prevA.click(_self.prevGame);
			_nextA.click(_self.nextGame);
			_toggleA.click(_self.toggleGame);
			
			_root.find(".game .info .teams .team").each(function()
			{
				var $team = $(this).find('span a').text().toLowerCase(),
					$score = $(this).find('em')
					;
					
				if ($score.text().length >= 3)
					$score.addClass('smaller');
			});
			
			updatePrevNextButtons();
		};
	
		// Initialization ------------------------------------------------------------------
		
		// bind all callbacks from configuration
		$.each(conf, bind);
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.gameDay = function(conf)
	{ 
		var opts = {
			hideFunc : function(element) { element.hide(); },
			showFunc : function(element) { element.show(); }
		}; 
		
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new GameDay($(this), opts);
			$(this).data("gameDay", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function Tabs(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
		    _ul = $(root).find('> ul'),
			_container = _root.find('.tabs-container'),
			_self = this,
			_lastTabIndex,
			_opts = {
				defaultIndex: 0,
				colWidth: null 
			}
			;
		$.extend(_opts, conf);

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			activate: function(index)
			{
				var $active = 'active',
					$eq = ':eq(' + index + ')'
					;
					
				conf.hideFunc(_ul.find('> li.' + $active).removeClass($active));
				conf.showFunc(_ul.find('> li' + $eq).addClass($active));

				_container.find('div.' + $active).removeClass($active);
				_container.find('div.activeLast').removeClass("activeLast");
				_container.find('div' + $eq).addClass($active);
				
				if (index == _lastTabIndex) {
					_container.find('div' + $eq).addClass("activeLast");
				}
			}
		});

		// Private methods -----------------------------------------------------------------

		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, function(e, args)
			{
				if (fn && fn.call(this, args.index) === false && args)
				{
					args.proceed = false;	
				}	
			});	
		};
		
		function initLayout()
		{
			_ul.find('> li').hide();
			var cHeaders = _ul.find('> li > ' + conf.header);
			_lastTabIndex = cHeaders.length-1;
			
			var tabTable = $('<table class="tabTable" cellpadding="10" cellspacing="0" width="100%" border="1"></table>').appendTo(_container);
			var tabBody = $('<tbody></tbody>').appendTo(tabTable);
			var tabRow = $('<tr></tr>').appendTo(tabBody);
			var targetWidth = _opts.colWidth == null ? _container.outerWidth() / cHeaders.length : _opts.colWidth;
			// converts all H5 tags to the tab elements
			cHeaders.each(function(index)
			{
				$('<td width="'+targetWidth+'"><div><a href="#">' + $(this).text() + '</a></div></td>').appendTo(tabRow);
				$(this).remove();
				
				_container.find('a:eq(' + index + ')').click(function()
				{
					_self.activate(index);
					return false;
				})
			});
			
			_container.find('div:first').addClass('first');
			_container.find('div:last').addClass('last');
			
			_self.activate(_opts.defaultIndex);
			
			_root.show();
		};

		// Initialization ------------------------------------------------------------------
		
		// bind all callbacks from configuration
		$.each(conf, bind);
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.tabs = function(conf)
	{ 
		var opts = {
			header : 'h5',
			hideFunc : function(element) { element.hide(); },
			showFunc : function(element) { element.fadeIn(); }
		}; 
		
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new Tabs($(this), opts);
			$(this).data("tab", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function PlayerStats(root, values)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_self = this,
			_sport = /sport-(\w+)/.exec(_root[0].className)[1],
			_data = SPORTSNET_PLAYER_STATS[_sport],
			_comparePosition,
			_comparePlayerId,
			_positionsContainer,
			_measuresContainer,
			_dimensionsContainer,
			_statsContainer,
			_selectedPosition,
			_selectedMeasure,
			_compareContainer,
			
			_changeHtml = '<span class="change">(<a href="#">change</a>)</span>',
			_clearHtml = '<div style="clear:both"></div>'
			;
	
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			selectPosition: function(sender)
			{
				if (_root.hasClass('position-selected'))
					return;
				
				var $radio = $(sender).parent().find('input:radio'),
					$position = $radio.val(),
					$data = findPosition($position)
					;

				if ($data == null)
					return false;

				_self.deselectPosition(null);
				_self.deselectMeasure(null);

				// deselectPosition will clear this, put it back
				$radio.attr('checked', 'true');
				
				_selectedPosition = $position;
				_root.addClass('position-selected');
				$(sender).parents('.radio').addClass('selected');
				
				// clear all dimensions
				_dimensionsContainer.html('');
				// create measures and stats
				createMeasure($data.measures);
				createStats($data.stats);

				bindEvents();
			},
			
			deselectPosition: function(sender)
			{
				_selectedPosition = null;
				_root.removeClass('position-selected');
				_root.removeClass('no-stats');
				_root.removeClass('no-dimensions');
				_positionsContainer
					.find('.radio').removeClass('selected')
					.find('input:radio').attr('checked', '')
					;
				_self.deselectMeasure(null);
				_self.activateButton(false);
				_measuresContainer.html('');
				_statsContainer.html('');
				_statsContainer.removeClass('opened');
			},
			
			selectMeasure: function(sender)
			{
				if (_root.hasClass('measure-selected'))
					return;
					
				var $radio = $(sender).parent().find('input:radio'),
					$measure = $radio.val(),
					$data = findPosition(_selectedPosition)
					;

				_self.deselectMeasure(null);
				
				// deselectMeasure clears all checks, so put it back
				$radio.attr('checked', 'true');
				
				_selectedMeasure = $measure;
				_root.addClass('measure-selected');
				$(sender).parents('.radio').addClass('selected');
				
				// only create dimension once
				if (_dimensionsContainer.html() == '')
					createDimensions($data.dimensions);
				
				bindEvents();
			},
			
			deselectMeasure: function(sender)
			{
				_selectedMeasure = null;
				_root.removeClass('measure-selected');
				_measuresContainer
					.find('.radio').removeClass('selected')
					.find('input:radio').attr('checked', '')
					;
				_measuresContainer.find('.radio').removeClass('selected');
				_dimensionsContainer.html('');
			},

			selectDimension: function(sender)
			{
				$(sender).parents('.items').find('.radio').each(function()
				{
					var $select = $(this).find('select'),
						$radio = $(this).find('input:radio')
						;
						
					if ($radio[0].checked == false && $select.length > 0)
						$select.attr('selectedIndex', 0);
				});
			},
			
			deselectDimension: function(sender)
			{
				_root.removeClass('prefilled-dimensions');
			},
			
			toggleStats: function(sender)
			{
				var $max = 5,
					$count = _statsContainer.find('input:checkbox[checked="true"]').length,
					$left = $max - Math.min($max, $count)
					;

				if ($count > $max && sender.checked == true)
					sender.checked = false;
					
				_statsContainer.find('.message .counter').html($left);
				
				_statsContainer
					.find('.radio input:checkbox[checked!="true"]')
					.parents('.radio')
						[($left == 0 ? 'add' : 'remove') + 'Class']('dim')
				;
			},
			
			toggleStatsSection: function(sender)
			{
				_statsContainer.toggleClass('opened');
				_root.removeClass('prefilled-stats');
			},
			
			setSelected: function(values)
			{
				function s(v) { return 'input[value="' + v + '"]'; };
				function check(sender) { sender.checked = true; };
				function open(container, callback, value)
				{
					if (value)
						return callback(container.find(s(value))[0]) != false;
					
					return false;
				};

				var $data,
					$position,
					$labels,
					$name
					;
				
				// handle compare values
				if (values.compare && values.compare.left != '' && values.compare.right != '')
				{
					var $players = SPORTSNET_PLAYERS[_sport],
						$leftData = findInArray($players, [0], values.compare.left),
						$rightData = findInArray($players, [0], values.compare.right)
						;
						
					_self.activateCompareTab();
					_self.setCompareValue(_compareContainer.find('input[name="left"]')[0], $leftData);
					_self.setCompareValue(_compareContainer.find('input[name="right"]')[0], $rightData);
					
					$position = $leftData[2];
				}
				else if (open(_positionsContainer, _self.selectPosition, values.position))
				{
					$position = values.position;
				}
				else
				{
					return;
				}

				$data = findPosition($position);
				open(_measuresContainer, _self.selectMeasure, values.measure);
				
				if (values.dimensions && values.dimensions.length > 0 && $data.dimensions)
				{
					var $dimensions = [];

					$labels = [];

					for (var $i = 0; $i < $data.dimensions.length; $i++)
						$dimensions = $dimensions.concat($data.dimensions[$i]);

					for (var $i = 0; $i < values.dimensions.length; $i++)
					{
						$name = values.dimensions[$i];
						
						if ($name == null || $name == '')
							continue;

						var $parts = $name.split(','),
							$label
							;
							
						$name = $parts[0];
						$label = findInArray($dimensions, 'name', $name).label;
						
						open(_dimensionsContainer, check, $name);
						
						if ($parts.length > 1)
						{
							var $team = $parts[1];
							
							_dimensionsContainer.find('select[name="' + field('dimension' + $i, $name) + '"]').val($team);
							
							// special case for 'Vs. TEAM NAME'
							if ($name == 'vs_team')
								$label = 'Vs. ' + findInArray(SPORTSNET_TEAMS[_sport], 0, $team)[2];
						}

						$labels.push($label);
					}

					if ($labels.length == 0)
						$labels.push('Defaults');
					
					_root.addClass('prefilled-dimensions');
					_dimensionsContainer.find('.title').after(''
						+ '<div class="prefilled">'
							+ $labels.join(', ')
							+ _changeHtml
						+ '</div>'
					);
				}

				// prefill 'Add stats' checkboxes
				if (values.stats && values.stats.length > 0)
				{
					$labels = [];
					
					for (var $i = 0; $i < values.stats.length; $i++)
					{
						$name = values.stats[$i];
						if ($name == null || $name == '')
							continue;
							
						$labels.push(findInArray($data.stats, 'name', $name).label);
						_statsContainer.find(s($name)).attr('checked', 'true');
						open(_statsContainer, _self.toggleStats, $name);
					}

					_root.addClass('prefilled-stats');
					_statsContainer.append(''
						+ '<div class="prefilled">'
							+ '<span class="label">Include:</span> '
							+ $labels.join(', ')
						+ '</div>'
					);
					
					// add a bit of extra space if more than 3 items were selected
					if ($labels.length > 3)
						_root.find('.buttonHolder').addClass('extra-space');
				}
				
				_self.activateButton(true);
			},
			
			getCompareHiddenField: function(name)
			{
				return _root.find('input[name="' + field('compare', name) + '"]');
			},
			
			setCompareValue: function(input, data)
			{
				if (data == null)
					return;
					
				var $player = data[1],
					$position = data[2],
					$id = data[0]
					;
				
				$(input).parent('.input').addClass('selected');
				$(input).siblings('.value').html($player);
				_self.getCompareHiddenField(input.name).val($id);
				
				// if left compare value was set, have to manipulate the right input field
				if (input.name == 'left')
				{
					_comparePlayerId = data[0];
					_comparePosition = $position;
					
					_compareContainer.find('.comment').html('Select another player');
					_compareContainer.find('.right input').attr('disabled', false);
				}
				
				if (input.name == 'right')
				{
					_self.activateButton(true);
				}
			},
			
			clearCompareValue: function(input)
			{
				var $parent = $(input).parent('.input');
				
				$parent.removeClass('selected');
				$parent.find('.value').html('');
				$(input).val('');
				$(input).hint();
				_root.find('.box').hide();
				_self.getCompareHiddenField(input.name).val('');
				_statsContainer.hide();
				_self.activateButton(false);
				
				if ($parent.hasClass('left'))
				{
					_comparePosition = null;
					_comparePlayerId = null;
					_compareContainer.find('.comment').html('');
					_compareContainer.find('.right input').attr('disabled', true);
					_self.clearCompareValue(_compareContainer.find('input[name="right"]'));
					_self.deselectPosition();
				}
				
				if ($parent.hasClass('right'))
				{
				}
			},
			
			activateCompareTab: function()
			{
				if (_self.activateTab(_root.find('.compare-tab a')) == false)
					return;

				createCompare();
				_compareContainer.show();
				_self.deselectPosition(null);
				_root.addClass('no-position no-measures');				
				_root.find('.box').hide();
				_root.data('no-position-by-compare', true);
				_root.data('no-measures-by-compare', true);
			},
			
			activateCustomTab: function()
			{
				if (_self.activateTab(_root.find('.custom-tab a')) == false)
					return;
				
				// removes no-position and no-measure from the _root if 
				// they were set by activating compare tab.
				function revertVisibility(name)
				{
					var $n = 'no-' + name + '-by-compare';
					
					if (_root.data($n) == true)
					{
						_root.removeClass('no-' + name);
						_root.data($n, null);
					}
				};
				
				revertVisibility('position');
				revertVisibility('measures');
				
				_root.find('.box').show();
				_root.find('input[name="' + field('compare', 'left') + '"]').val('');
				_root.find('input[name="' + field('compare', 'right') + '"]').val('');
				_self.deselectPosition(null);
				_compareContainer.html('');
				_compareContainer.hide();
				_comparePosition = null;
				_comparePlayerId = null;
				
				// have to select default if it's present
				if (findPosition('default') != null)
					_self.selectPosition(_positionsContainer.find('input[value="default"]'));
			},
			
			activateTab: function(a)
			{
				var $div = $(a).parent('div');
				
				if ($div.hasClass('on'))
					return false;
					
				$(a).parents('.tabs').find('.on').removeClass('on');
				$div.addClass('on');
				
				return true;
			},
			
			activateButton: function(activate)
			{
				_root.find('.buttonHolder .button')[(activate ? 'remove' : 'add') + 'Class']('buttonInactive');
			}
		});
	
		// Private methods -----------------------------------------------------------------
		
		function getWidth(target)
		{
			return target.width()
				+ parseInt(target.css('padding-left'))
				+ parseInt(target.css('padding-right'))
				+ parseInt(target.css('margin-left'))
				+ parseInt(target.css('margin-right'))
				;
		};
		
		function setSelected(target, selected)
		{
			$(target)[(selected ? 'add' : 'remove') + 'Class']('selected');
		};
		
		function findInArray(array, fieldname, value)
		{
			for (var $i = 0; $i < array.length; $i++)
				if (array[$i][fieldname] == value)
					return array[$i];
					
			return null;
		};
		
		function findPosition(name)
		{
			return findInArray(_data, 'name', name);
		};
		
		function field(name, param)
		{
			return 'player_stats[' + name + '][' + (param == null ? '' : param)+ ']';
		};
		
		function sortByField(array, field)
		{
			return array.sort(function(a, b)
			{
				a = a[field];
				b = b[field];
				
				if (a > b)
					return 1;
				else if (a < b)
					return -1;
				else
					return 0;
			});
		};
		
		/**
		 * Adds <div style='clear: both' /> after Nth .radio element in the container.
		 */
		function setColumns(container, columns)
		{
			columns =  columns || 3;
			$(container).find('.radio:nth-child(' + columns + 'n)').after('<div style="clear: both"></div>');
		};
		
		function createCompare()
		{
			if (_compareContainer.html() != '')
				return;
			
			var $html = ''
				+ '<div class="input left float sn-input">'
					+ '<input type="text" class="sn-input" name="left" title="Type player\'s name" />'
					+ '<div class="value float"></div>'
					+ _changeHtml
				+ '</div>'
				+ '<div class="vs float">vs.</div>'
				+ '<div class="input right float sn-input">'
					+ '<input type="text" class="sn-input" name="right" title="Player 2" disabled="true" />'
					+ '<div class="comment"></div>'
					+ '<div class="value float"></div>'
					+ _changeHtml
				+ '</div>'
				+ _clearHtml
			;
			
			_compareContainer.html($html);
				
			_compareContainer.find('.change a').click(function()
			{
				_self.clearCompareValue($(this).parents('.input').find('input:textbox'));
				return false;
			});
			
			_compareContainer.find('input:textbox')
				.hint()
				
				.autocomplete(SPORTSNET_PLAYERS[_sport], {
					minChars: 0,
					width: 200,
					matchContains: true,
					autoFill: false,
					formatItem: function(row, i, max) 
					{
						// make sure we show players of the same position in the drop down on the right
						if (_comparePosition != null && row[2] != _comparePosition)
							return false;

						// make sure we don't show the same player in the right drop down
						if (_comparePlayerId != null && row[0] == _comparePlayerId)
							return false;
							
						return row[1];
					},
					formatMatch: function(row, i, max) 
					{
						return row[1];
					},
					formatResult: function(row) 
					{
						return row[1];
					}
				})
				
				.bind('result', function(e, data)
				{
					_self.setCompareValue(this, data);
				})
			;
		};
		
		function createPositions()
		{
			var $html = ''
				+ '<div class="title">Position:</div>'
				+ '<div class="items">'
				;

			for (var $i = 0; $i < _data.length; $i++)
			{
				var $position = _data[$i],
					$value = $position.name,
					$id = 'sport-position-' + $value 
					;
				
				$html += ''
					+ '<div class="radio position">'
						+ '<input type="radio" id="' + $id + '" name="' + field('position') + '" value="' + $value + '" />'
						+ '<div class="label-box">'
							+ '<label for="' + $id + '">' + $position.label + '</label>'
						+ '</div>'
					+ '</div>'
					;
			}
			
			$html += ''
				+ '</div>'
				+ _changeHtml
				+ _clearHtml
				;

			_positionsContainer.html($html);
			
			// check if there's just one position in current sport and act accordingly
			if (_data.length == 1 && _data[0].name == 'default')
			{
				_positionsContainer.hide();
				_root.addClass('no-position');
				_self.selectPosition(_positionsContainer.find('input:radio')[0]);
			}
		};

		function vsTeam(name, selected)
		{
			var $teams = sortByField(SPORTSNET_TEAMS[_sport], 2),
				$html = ''
					+ '<select size="1" name="' + name + '">'
						+ '<option value=""></option>'
				;
				
			for (var $i = 0; $i < $teams.length; $i++)
				$html += '<option value="' + $teams[$i][0] + '">' + $teams[$i][2] + '</option>';
			
			$html += '</select>'
			
			return $html;
		};
		
		function createMeasure(measures)
		{
			var $html = ''
				+ '<div class="title">Sort by:</div>'
				+ '<div class="items">'
				;

			for (var $i = 0; $i < measures.length; $i++)
			{
				var $measure = measures[$i],
					$value = $measure.name,
					$id = 'sport-measure-' + $value
					;
				
				$html += ''
					+ '<div class="radio measure">'
						+ '<input type="radio" id="' + $id + '" name="' + field('measure') + '" value="' + $value + '" />'
						+ '<div class="label-box">'
							+ '<label for="' + $id + '">' + $measure.label + '</label>'
						+ '</div>'
					+ '</div>'
					;
			}
			
			$html += ''
				+ '</div>'
				+ _changeHtml
				+ _clearHtml
				;
			
			var $hasPositions = _positionsContainer.is(':visible');
			
			_root.removeClass('prefilled-measure');
			_measuresContainer.html($html);
			setColumns(_measuresContainer, $hasPositions ? 2 : 3);

			if ($hasPositions)
				_measuresContainer.find('.items').css('margin-left', getWidth(_positionsContainer));
		};
		
		function createStats(stats)
		{
			if (stats == null || stats.length == 0)
			{
				_root.addClass('no-stats');
				return;
			}
						
			var $html = ''
				+ '<a href="#" class="more">Add stats</a>'
				+ '<div class="message">Choose up to 5 additional stats (<span class="counter">5</span> left)</div>'
				+ '<div class="items">'
				;
				
			for (var $i = 0; $i < stats.length; $i++)
			{
				var $item = stats[$i],
					$value = $item.name,
					$id = 'sport-stats-' + $value 
					;
				
				$html += ''
					+ '<div class="radio stats">'
						+ '<input type="checkbox" id="' + $id + '" name="' + field('stats', '') + '" value="' + $value + '" />'
						+ '<div class="label-box">'
							+ '<label for="' + $id + '">' + $item.label + '</label>'
						+ '</div>'
					+ '</div>'
					;
			}
			
			$html += ''
				+ '</div>'
				+ '<div style="clear: both" class="toggled-clear"></div>'
				;
			
			_root.removeClass('prefilled-stats');
			_statsContainer.html($html);
			setColumns(_statsContainer);
		};
		
		function createDimensions(dimensions)
		{
			if (dimensions == null || dimensions.length == 0)
			{
				_root.addClass('no-dimensions');
				return;
			}
			
			var $html = ''
				+ '<div class="title">Only show:</div>'
				+ '<div class="items-group">'
				;
				
			for (var $dimensionIndex = 0; $dimensionIndex < dimensions.length; $dimensionIndex ++)
			{
				var $dimensions = dimensions[$dimensionIndex];
				
				$html += '<div class="items">';
				
				for (var $i = 0; $i < $dimensions.length; $i++)
				{
					var $dimension = $dimensions[$i],
						$value = $dimension.name,
						$id = 'sport-dimension-' + $dimensionIndex + '-' + $value,
						$vs = ($value == 'vs_team')
						;
				
					$html += ''
						+ '<div class="radio dimension ' + ($vs ? 'vs' : '') + '">'
							+ '<input type="radio" id="' + $id + '" name="' + field('dimension' + $dimensionIndex) + '" value="' + $value + '" />'
							+ '<div class="label-box">'
								+ '<label for="' + $id + '">' + $dimension.label + '</label>'
								+ ($vs ? vsTeam(field('dimension' + $dimensionIndex, 'vs_team')) : '')
							+ '</div>'
						+ '</div>'
						;
				}
				
				$html += ''
				 		+ _clearHtml
					+ '</div>'
					;
			}
			
			$html += '' 
					+ _clearHtml
				+ '</div>'
				;
			
			_root.removeClass('prefilled-dimensions');
			_dimensionsContainer.html($html);
			_dimensionsContainer.find('.items:first').addClass('first');
			_dimensionsContainer.find('.items:last').addClass('last');
			
			setColumns(_dimensionsContainer);
		};
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
							
			_root.html();
			_root.html(''
				+ '<div class="tabs">'
					+ (SPORTSNET_TEAM_STATS_TARGET ? '<div class="arrow" style="float:right;"><a href="'+SPORTSNET_TEAM_STATS_TARGET+'" class="today-link">Team Stats</a></div>' : '')
					+ '<div class="tab-section custom-tab on"><a href="#">Custom Stat Search</a></div>'
					+ '<div class="tab-section compare-tab"><a href="#">Compare With</a></div>'
				+ '</div>'
				+ _clearHtml
				+ '<div class="compare"></div>'
				+ '<form method="post" name="statsForm" id="statsForm" action="' + SPORTSNET_PLAYER_STATS_TARGET + '">'
					+ '<input type="hidden" name="' + field('compare', 'left') + '" />'
					+ '<input type="hidden" name="' + field('compare', 'right') + '" />'
					+ '<div class="box">'
						+ '<div class="section position"></div>'
						+ '<div class="section measures"></div>'
						+ '<div class="section dimensions"></div>'
						+ _clearHtml
					+ '</div>'
					+ '<div class="section stats"></div>'
					+ '<div class="buttonHolder">'
						+ '<a href="#" class="button buttonInactive"><span>Get Stats Now</span></a>'
					+ '</div>'
				+ '</form>'
				);
				
			// add non-functional bits for tab visuals
			_root.find('.tabs > div > a')
				.before('<span class="left"></span>')
				.after('<span class="right"></span>')
				;

			_compareContainer = _root.find('.compare');
			_positionsContainer = _root.find('.position');
			_measuresContainer = _root.find('.measures');
			_dimensionsContainer = _root.find('.dimensions');
			_statsContainer = _root.find('.stats');
			
			_compareContainer.hide();
			createPositions();
			_self.setSelected(values);
			
			bindEvents();
		};
		
		// rebinds all radio buttons, checkboxes and '(change)' links
		function bindEvents()
		{
			_positionsContainer.find('input:radio').unbind().click(function()
			{
				_self.selectPosition(this);
				_self.activateButton(true);
			});
			
			_positionsContainer.find('.change a').unbind().click(function()
			{
				_self.deselectPosition(this);
				return false;
			});

			_measuresContainer.find('input:radio').unbind().click(function()
			{
				_self.selectMeasure(this);
			});

			_measuresContainer.find('.change a').unbind().click(function()
			{
				_self.deselectMeasure(this);
				return false;
			});
			
			_dimensionsContainer.find('input:radio').unbind().click(function()
			{
				_self.selectDimension(this);
			});

			_dimensionsContainer.find('.prefilled .change a').unbind().click(function()
			{
				_self.deselectDimension(this);
				return false;
			});
						
			_statsContainer.find('input:checkbox').unbind().click(function()
			{
				_self.toggleStats(this);
			});
			
			_statsContainer.find('a').unbind().click(function()
			{
				_self.toggleStatsSection(this);
				return false;
			});
			
			_root.find('.compare-tab a').unbind().click(function()
			{
				_self.activateCompareTab();
				return false;
			});

			_root.find('.custom-tab a').unbind().click(function()
			{
				_self.activateCustomTab();
				return false;
			});

			_root.find('a.button').click(function()
			{
				if ($(this).hasClass('buttonInactive') == false)
					$("#statsForm").submit();
					
				return false;
			});
			
			// make sure that all selects activate their respective radios
			_dimensionsContainer.find('select').unbind().change(function()
			{
				$(this).parents('.radio').find('input:radio').attr('checked', true);
			});
		};
		
		// Initialization ------------------------------------------------------------------

		initLayout();
	};

	// jQuery plugin implementation
	$.fn.playerStats = function(values)
	{ 
		this.each(function() 
		{
			var $instance = new PlayerStats($(this), values);
			$(this).data('playerStats', $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function DateManager(root, conf)
	{	
		// Private fields -------------------------------------------------------------------

		var _root = $(root),
			_next = _root.find('.next'),
			_prev = _root.find('.prev'),
			_input = _root.find('input'),
			_curDate = _input.val(),
			_changeDateButtons = [],
			_cookieName = "sn_date",
			_cookieValue = null;
			_self = this
			;
			
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			changeDate: function (_date, _increment) {
				var newDateObj = new Date(_date.getFullYear(), _date.getMonth(), (_date.getDate() + _increment));
				return newDateObj;
			},
			onOpenDatePick: function () {
				_changeDateButtons.each(function(){
					this.style.display = "none";
				});
			},
			onCloseDatePick: function () {
				_changeDateButtons.each(function(){
					this.style.display = "block";
				});
				//_changeDateButtons.show();
			}
		});

		// Private methods -----------------------------------------------------------------

		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn))
				$(_self).bind(name, fn);
		};
				
		function initLayout(){
			if (conf.highlightWeek == true)
				$('#datepicker-wrapper').addClass('weeks');

			// generate layout -----------------------------------------
			//console.log("curDate: "+curDate)
			$('#embedded-datepicker').datepick($.extend({
				mandatory: true,
				showDefault: true,
				numberOfMonths: 3,
				showCurrentAtPos: 2,
				stepMonths: 3,
				showOtherMonths: true,
				showOn: 'both',
				buttonImageOnly: true,
				buttonImage: '/assets/img/date_picker/calendar.gif',
				dateFormat: 'MM d, yy',
				changeMonth: false,
				changeYear: false,
				showAnim: 'slideDown',
				duration: 100,
				paddingTop: 5,
				paddingLeft: 0,
				onClose: function(){
					_self.onCloseDatePick();
				},
				onOpen: function(){
					_self.onOpenDatePick();
				}
			}, conf));
			
			_changeDateButtons = $('.change-date');
			_changeDateButtons.click(function(){
				var input = $.datepick._getInst($("#embedded-datepicker")[0]);
				var curDisplayDate = $.datepick._getDate(input);
				var newDate;
				if ($(this).hasClass('next')) {
					newDate = _self.changeDate(curDisplayDate, (conf.highlightWeek == true ? 7 : 1));
				}
				else {
					newDate = _self.changeDate(curDisplayDate, (conf.highlightWeek == true ? -7 : -1));
				}
				$.datepick._setDate(input, newDate);
				$('#embedded-datepicker').trigger('change');
				return false;
			});
			_changeDateButtons.hover(
				function(){
					$(this).addClass("hover");
				},
				function(){
					$(this).removeClass("hover");
				}
			);
			
			$('#embedded-datepicker').change(function(){
				$('#dateInput').val($.datepick.formatDate('yymmdd', $.datepick._getDate($.datepick._getInst($("#embedded-datepicker")[0]))));
				$('#datepickerForm').submit();
			});
			
			$(window).resize(function(){
				$.datepick._hideDatepick();
			});
		}

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.dateManager = function(conf)
	{
		// update dates from array to match what we expect
		if ($.isArray(conf.selectedDates))
		{
			var $dates = conf.selectedDates;
			
			for (var $i = 0; $i < $dates.length; $i++)
			{
				var $date = new Date($dates[$i] * 1000);
				$date.setHours(0);
				$dates[$i] = $date.getTime(); 
			}
		}
		
		this.each(function()
		{
			var $instance = new DateManager($(this), conf);
			$(this).data("dateManager", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function TeamFeatureStory(root)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_opts = {
				debug: false
			}
			;
	
		// Public methods ------------------------------------------------------------------
//		$.extend(_self, {
//		});
	
		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					trace(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
		
		function scaleSummary()
		{
			var availHeight = $(_root.parent()).parent().outerHeight();
			availHeight -= _root.outerHeight();
			debug("availHeight: " + availHeight);
			var summaryElem = _root.find('.summary:first');
			
			summaryElem.css({height:"auto"});
			debug("summaryElem.height(): " + summaryElem.height());
			if (summaryElem.height() > availHeight) {
				summaryElem.css({height:"0px"});
			
				var lineHeight = Math.ceil((summaryElem.css('line-height').split('p'))[0]);
				var numRows = Math.floor(availHeight / lineHeight);
				var summaryHeight = numRows * lineHeight;
				
				summaryElem.height(summaryHeight);
			}
			
			try {
				sportsnetPage.registerInit({
					_expression: ".ellipsis",
					_functionRef: "ellipsis",
					_rank: "DISPLAY"
				});
			}
			catch (e) {
				summaryElem.ellipsis();
			}
		};
	
		function init()
		{	
			scaleSummary();
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.teamFeatureStory = function()
	{
		this.each(function()
		{
			var $instance = new TeamFeatureStory($(this));
		});
		
		return this;
	};
})(jQuery);
/* begin MiniStats */
(function($)
{	
	// constructor
	function ArticleTools(root)
	{	
		// Private fields ------------------------------------------------------------------
	
		var _root = $(root),
			_self = this,
			_scaleButtons,
			_opts = {
				debug: false
			}
			;
	
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			setCopySize: function(copySize, dontDispatch)
			{
				debug("setCopySize");
				
				var articleBody = $("div.article-body");
				
				_self.clearButtonStates();
				_root.find('.sizer-' + copySize).addClass("on");
				
				articleBody.removeClass("small");
				articleBody.removeClass("medium");
				articleBody.removeClass("large");
				
				articleBody.addClass(copySize);

//				if (dontDispatch != true)
//				{
				$.cookie('sn_articleTextSize', copySize, {path:'/'});
//					$(document.body).trigger('setCopySize', copySize);
//				}
			},
			
//			onSetCopySize: function(e, copySize)
//			{
//				debug("setCopySize");
//				_self.setCopySize(copySize, true /* don't dispatch again to avoid loops */);
//			},
			
			clearButtonStates: function()
			{
				debug("clearButtonStates");
				_scaleButtons.each(function(){
					var _this = $(this);
					_this.removeClass("on");	
				}
				);
			}
		});
	
		// Private methods -----------------------------------------------------------------
	
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					console.log(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
		
		function init()
		{	
			debug("ArticleTools init");
			_scaleButtons = _root.find("a");

			_scaleButtons.each(function(){
				var size = /\btext-sizer:\s*(\S+)\b/.exec(this.className)[1];
				$(this)
					.data('size', size)
					.addClass('sizer-' + size)
					.click(function()
					{
						_self.setCopySize($(this).data('size'));
						return false;
					})
				;
			}
			);
			
			//$(document.body).bind('setCopySize', _self.onSetCopySize);
			
			var cookieSize = $.cookie('sn_articleTextSize');
			if (cookieSize != null) {
				debug("found cookie:" + cookieSize);
				_self.setCopySize(cookieSize);
			} else {
				debug("no cookie - sn_articleTextSize");
			}
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};

	// jQuery plugin implementation
	$.fn.articleTools = function()
	{
		this.each(function()
		{
			var $instance = new ArticleTools($(this));
		});
		return this; 
	};
})(jQuery);
/* end MiniStats */
(function($)
{	
	// constructor
	function Gallery(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
			_self = this,
			_thumbs,
			_featureContainer,
			_selectedIndex,
			_playIntervalId = 0,
			_playButton,
			_scroller
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			showImage: function(index, keepAutoPlaying)
			{
				var $thumb = $(_thumbs[index]),
					$a = $thumb.find('a'),
					$src = $a.data('src')
					;
				
				_featureContainer.html('<img src="' + $src + '" class="feature img">');
				
				// fade feature image in if not in IE6
				if ($.browser.msie6 == false)
					conf.showFunc(_featureContainer.find('.feature').hide());
				
				// update 'N of X' label
				_root.find('.controls .position').html((index + 1) + ' of ' + _thumbs.length);
				
				// update text labels
				_root.find('.middle > .text').html($thumb.find('.text').html());
				_root.find('.bottom > .meta').html($thumb.find('.meta').html());
				
				// place selection on the correct thumb
				_thumbs.find('.selection').remove();
				$(_thumbs[index]).append('<div class="selection"></div>');
				
				var $expectedPageIndex = Math.floor(index / _scroller.getPageSize());
				
				if (_scroller.getPageIndex() != $expectedPageIndex)
					_scroller.setPage($expectedPageIndex)
				
				_selectedIndex = index;
				
				if (keepAutoPlaying != true && _playIntervalId > 0)
					_self.pause();
			},
			
			prevImage: function()
			{
				if (--_selectedIndex < 0)
					_selectedIndex = _thumbs.length - 1;
					
				_self.showImage(_selectedIndex)
//				_self.updateAds();
			},
			
			nextImage: function(keepAutoPlaying)
			{
				// if next image would be looped and we are autoplaying, then pause
				if (keepAutoPlaying == true && _selectedIndex >= _thumbs.length)
				{
					_self.pause();
					++_selectedIndex;
				}
				else if (++_selectedIndex >= _thumbs.length)
				{
					_selectedIndex = 0;
					keepAutoPlaying = false;
				}
				
				_self.showImage(_selectedIndex, keepAutoPlaying);
//				_self.updateAds();
			},
			
			play: function()
			{
				_self.pause();
				_playIntervalId = setInterval(function() { _self.nextImage(true /* keep autoplaying */) }, conf.playbackDelay);
				_playButton.addClass('pause');
				_self.nextImage(true);
			},
			
			pause: function()
			{
				_playButton.removeClass('pause');
				clearInterval(_playIntervalId);
				_playIntervalId = 0;
			},
			
			playPause: function()
			{
				if (_playIntervalId > 0)
					_self.pause();
				else
					_self.play();
			},
			updateAds: function()
			{
				var $bbAds = $('.right-col-ads').find('.ad'),
					$curBbAd = $bbAds.not('.hidden'),
					$hidBbAds = $bbAds.filter('.hidden'),
					$nextBbAd = $hidBbAds[Math.floor(Math.random() * $hidBbAds.length)];				
					$lbAds = $('.ads-topnav').find('.ad'),
					$curLbAd = $lbAds.not('.hidden'),
					$hidLbAds = $lbAds.filter('.hidden'),
					$nextLbAd = $hidLbAds[Math.floor(Math.random() * $hidLbAds.length)];	
					$ftAds = $('.ads').find('.ad'),
					$curFtAd = $ftAds.not('.hidden'),
					$hidFtAds = $ftAds.filter('.hidden'),
					$nextFtAd = $hidFtAds[Math.floor(Math.random() * $hidFtAds.length)];	
				
				$($curBbAd).addClass('hidden');				
				$($nextBbAd).removeClass('hidden');
				$($curLbAd).addClass('hidden');
				$($nextLbAd).removeClass('hidden');				
				$($curFtAd).addClass('hidden');
				$($nextFtAd).removeClass('hidden');				
			}
		});

		// Private methods -----------------------------------------------------------------
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
			
			_featureContainer = _root.find('.feature-container');
			
			// set up scrolling panel
			_scroller = _root.find('.scrolling-panel').scrollingPanel({ size: '4x3' }).data('scrollable');
			
			_thumbs = _root.find('.scroll-container ul li');
			
			_thumbs.find('a')
				.each(function(index)
				{
					var $img = $(this).find('img')[0];
					$(this)
						.wrap('<div class="thumb img" style="background-image: url(' + $img.alt + ')">')
						.data('src', $img.src)
						.data('index', index)
						.html('')
					;
				})
				.unbind()
				.click(function()
				{
					_self.showImage($(this).data('index'));
//					_self.updateAds();
					return false;
				})
			;
			
			var $controls = _root.find('.top .controls');
			
			$controls.find('.prev').click(function()
			{
				_self.prevImage();
				return false;
			});

			$controls.find('.next').click(function()
			{
				_self.nextImage();
				return false;
			});
			
			_playButton = $controls.find('.play').click(function()
			{
				_self.playPause();
				return false;
			});
			
			// calculate height of the middle section
			_root.find('.middle').css('height',
				_root.find('.sidebar').height() - 
				_root.find('.bottom').height() - 
				_root.find('.top').height()
				- 10 // some spacing
			);
			
			// show first image
			_self.showImage(conf.index || 0);
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.gallery = function(conf)
	{ 
		var opts = {
			hideFunc : function(element) { element.hide(); },
			showFunc : function(element) { element.fadeIn(); },
			playbackDelay : 5000
		}; 
		
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new Gallery($(this), opts);
			$(this).data("gallery", $instance);	
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function GalleryFeature(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
			_self = this
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
		});

		// Private methods -----------------------------------------------------------------
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.galleryFeature = function(conf)
	{ 
		var opts = {}; 
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new GalleryFeature($(this), opts);
			$(this).data("galleryFeature", $instance);	
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function GalleryRecent(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
			_self = this
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
		});

		// Private methods -----------------------------------------------------------------
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
				
			_root.find('.scrolling-panel').scrollingPanel({ size: 2 });
			
			_root.find('.thumb').each(function()
			{
				$(this).hover(function() {											// Hover function added 
									   		$(this).addClass('hover');				// to override IE6 behaviour.
									   }, function() {								//	
										   	$(this).removeClass('hover');			//	Gord 09/08/2009
									   });
				
				var $url = $(this).find('a').attr('href');
				$(this).find('.img').click(function()
				{
					window.location = $url;
					return false;
				});
			});
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.galleryRecent = function(conf)
	{ 
		var opts = {}; 
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new GalleryRecent($(this), opts);
			$(this).data("galleryRecent", $instance);	
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function GalleryList(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
			_self = this
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
		});

		// Private methods -----------------------------------------------------------------
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
							
			_root.find('.thumb').each(function()
			{
				var $url = $(this).find('.meta a').attr('href');
				$(this).find('.img').click(function()
				{
					window.location = $url;
					return false;
				});
				$(this).hover(
					function(){
						$(this).addClass("hover");
					},
					function(){
						$(this).removeClass("hover");
					}
				);
			});
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.galleryList = function(conf)
	{ 
		var opts = {}; 
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new GalleryList($(this), opts);
			$(this).data("galleryRecent", $instance);	
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function MyHeadlinesLineUp(root)
	{	
		// Private fields -------------------------------------------------------------------

		var _root = $('body'),
			_curLeague = $('#league-selector').val(),
			_myLineUpCookie = "sn_myHeadlinesLineUp",
			_myRegionCookie = "sn_region",
		    _addString = "Add  <img src='/assets/img/my_headlines_lineup/plus_icon.gif' />",
			_removeString = "Remove  <img src='/assets/img/my_headlines_lineup/minus_icon.gif' />",
			_self = this,
			_myLineUp = new Array(),
			_myEmptyLogos = $('#my-lineup-logos').find('.empty');
			_cookieCheck = null,
			_imgPath = "/assets/img/team_logos/scores/59x59/"
			_opts = {
				debug: false
			}
			;  

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			
			//check for channel cookie
			doCookieCheck: function (whichCookie)
			{
				var $myCookie = whichCookie;
				var c = $.cookies.get($myCookie);
				if (c != null) {
					_myLineUp = c.split(',');
					return true;
				} else {
					//alert("doCookieCheck: cookie: "+c);
					return false;
				}
			},	
			
			//set user's channel cookie
			doCookieSet: function (whichCookie, whichValue)
			{
				var $tmp = window.location.href,
					$url = $tmp.split('/'),
					$loc = $url[2].split('.'),
					$dom = '.'+$loc[1]+'.'+$loc[2];
				 var cookieOptions = {
				    path: '/',
					domain: $dom,//'.pairsite.com', //'.sportsnet.ca',
				    hoursToLive: 90000,
				    secure: false
				  }
				var $cookie = whichCookie;
				var $value = whichValue;
				$.cookies.set($cookie, $value, cookieOptions);
				_self.lineupInfoSaved();
			},

			lineupInfoSaved: function ()
			{
				$('p#my-lineup-status').animate({opacity:'toggle'}, 150, function(){
																				  $('p#my-lineup-status').html('<span style="padding: 3px 5px; display: block; background-color: rgb(255, 255, 136)"><b>Your changes have been saved.</b></span>').animate({opacity:'toggle'}, 100);
				});
				//$('p#my-lineup-status').html('<span style="padding: 3px 5px; display: block;"><b>Your changes have been saved.</b></span>').css({'background-color': 'rgb(255, 255, 136)'}).animate({opacity:'toggle'}, 100);
				//$('p#my-lineup-status').css({'background-color': 'rgb(255, 255, 136)'});
				setTimeout(function(){
									$('p#my-lineup-status').animate({opacity:'toggle'}, 150, function(){$('p#my-lineup-status').html('You can follow up to 6 teams.').animate({opacity:'toggle'}, 100);});
									//$('p#my-lineup-status').animate({opacity:'toggle'}, 100).html('You can follow up to 6 teams.').css({'background-color': none});
									},650);
			},
			
			activate: function(obj)
			{
				var $el = obj,
				    $wrap = $el.parents('tr'),
					$img = $wrap.find('.team-logo');
					
				$el.find('a').html(_addString);
				$wrap.css({'background-color' : '#EBEBEB'});
				if ($.browser.msie6 == true){
					$img.css({filter: "alpha(opacity = 100)"});
					$($img.find('img')).css({filter: "alpha(opacity = 100)"});
				} else {
					$img.fadeTo('fast',1);
				}
				$el.toggleClass('selected');
				_self.removeFromLineUp($el.attr('id'));
			},
			
			deactivate: function(obj) 
			{
				var $el = obj,
				    $wrap = $el.parents('tr'),
					$img = $wrap.find('.team-logo');
					
				$el.find('a').html(_removeString);
				$wrap.css({'background-color' : '#FFFFFF'});
				if ($.browser.msie6 == true){
					$img.css({filter: "alpha(opacity = 50)"});
					$($img.find('img')).css({filter: "alpha(opacity = 50)"});
				} else {
					$img.fadeTo('fast',0.5);
				}
				
				$el.toggleClass('selected');

			},
			
			addToLineUp: function(id)
			{
				clearTimeout();
				var str = id.split('_'),
					$league = str[0],
					$team = str[1],
					$cVal = $league+'|'+$team;
					
					_myLineUp.push($cVal);
					_self.doCookieSet(_myLineUpCookie, _myLineUp);
					_self.updateLineUp($league, $team);
				
			},
			
			removeFromLineUp: function(id)
			{
				clearTimeout();
				var str = id.split('_'),
					$league = str[0],
					$team = str[1];
					$cVal = $league+'|'+$team,
					curNode = $('#my-lineup-logos').find('#my_'+id),
					curImg = $(curNode).find('.transparentPng');
					

					_myLineUp = $.grep(_myLineUp,function(value){
						return value != $cVal;
					});
					if (_myLineUp.length == 0) {
						$.cookies.del(_myLineUpCookie);
						$('p#my-lineup-status').html('<b>You are not following any teams.</b>');//alert("Maximum teams reached! At least one team must be removed before you can follow another.  " + $('#my-lineup-logos').find('.empty').length);
					}
					else {
						$('p#my-lineup-status').html('You can follow up to 6 teams.');//alert("Maximum teams reached! At least one team must be removed before you can follow another.  " + $('#my-lineup-logos').find('.empty').length);
						_self.doCookieSet(_myLineUpCookie, _myLineUp);
					}
					curImg.fadeOut('normal', function() {
						$(curImg).attr('src', '');
						$(curNode).find('a').hide();
						$(curNode).addClass('empty');
						$(curNode).removeAttr('id');
						$(curNode).removeClass("hover");
						$('#my-lineup-logos').append($(curNode));
					});
					$('#my-lineup-logos').sortable('refresh');
			},
			
			initLineUp: function()
			{
				for (var i=0; i<_myLineUp.length; i++) {
					_self.debug("_myLineUp[i]: "+ _myLineUp[i]);
					_self.debug("_myEmptyLogos[i]: "+ _myEmptyLogos[i]);
					
					var str = _myLineUp[i].split('|'),
						curLeague = str[0],
						curTeam = str[1],
						curSport = _self.getSport(curLeague),
						curNode = _myEmptyLogos[i],
						curImg = $(curNode).find('.transparentPng'),
						id = curLeague + '_' + curTeam,
						curId = 'my_' + curLeague + '_' + curTeam;
					if ($.browser.msie6 == true) {
						curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.gif');
					} else {
						curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.png');
					};
					curImg.addClass('logo');
					curImg.fadeIn('fast');
					$(curNode).toggleClass('empty');
					$(curNode).attr('id', curId); 
					_self.deactivate($('#'+id));
				}
				_self.initSortable();
			},
			
			updateLineUp: function(league, team) {
				var curNode = $('#my-lineup-logos').find('.empty')[0],
					curImg = $(curNode).find('.transparentPng'),
					curLeague = league,
					curTeam = team,
					curSport = _self.getSport(curLeague),
					curId = 'my_' + curLeague + '_' + curTeam;
					
				if ($.browser.msie6 == true) {
					curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.gif');
				} else {
					curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.png');
				};
				curImg.addClass('logo');
				curImg.fadeIn('fast');
				$(curNode).toggleClass('empty');
				$(curNode).attr('id', curId); 
				$('p#my-lineup-status').html('You can follow up to 6 teams.');//alert("Maximum teams reached! At least one team must be removed before you can follow another.  " + $('#my-lineup-logos').find('.empty').length);
			},
			
			initSortable: function() {
				
				$('#my-lineup-logos').sortable({ 
											   	items: "li:not('.empty')",
												tolerance: 'pointer',
												cursorAt: 'top',
												revert: '100',
												cancel: '.empty',
												start: function(event, ui) {
																		ui.item.unbind('mouseenter mouseleave');
																		ui.item.removeClass('hover');
																		ui.item.find('a').hide();
																		//TODO - disable hover state
																	},
												update: function() {
																		//TODO - activate hover state
																		
																		var $cookie = $('#my-lineup-logos').sortable('toArray');
																		for(var i = 0; i<$cookie.length; i++) {
																			var curNode = $cookie[i],
																				str = curNode.split('_');
																				
																			$cookie[i] = str[1] + "|" + str[2];	
																		}
																		_self.doCookieSet( _myLineUpCookie, $cookie);
																	},
												stop: function(event, ui) {
																		ui.item.hover(function() {
																				if($(this).hasClass('empty') == false) {
																					$(this).find('a').toggle();
																					$(this).addClass("hover");
																				} else {
																					$(this).addClass("emptyHover");
																				}
															
																			}, function() {
																				if ($(this).hasClass('empty') == false) {
																					$(this).find('a').toggle();
																					$(this).removeClass("hover");
																				} else {
																					$(this).removeClass("emptyHover");
																				}
																		});
																		//ui.item.addClass('hover');
																		//ui.item.find('a').show();
																	}					
											});
				$('#my-lineup-logos').disableSelection();							
			},
			killSortable: function() {
				$('#my-lineup-logos').sortable('destroy');
			},
			
			getSport: function(league) 
			{
					var sport = null;
					
					switch(league){
						case "nhl":
							sport = "hockey";
							break;
						case "mlb":
							sport = "baseball";
							break;
						case "nfl": 
							sport = "football";
							break;
						case "cfl":
							sport = "football";
							break;
						default:
							sport = "basketball";		
							break;
							
					}
					return sport;
			},
			
			reloadPage: function () 
			{
				location.reload();
			},

			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						trace(str);
					} 
					catch (e) {
						alert(str);
					}
				}
			}
		});

		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	

			$("#"+_curLeague).toggleClass('hidden');

			_cookieCheck = _self.doCookieCheck('sn_myHeadlinesLineUp');
			
			if (_cookieCheck == true){
				_self.initLineUp();	
			} else {
				_myLineUp = window.sn_HeadlinesLineUp.split(",");
				_self.doCookieSet(_myLineUpCookie, _myLineUp);
				_self.initLineUp();
			};
		
			$('.select-team').click(function(){
				var $this = $(this);
				if ($this.hasClass('selected')) {
					_self.activate($this);
				} else {
					if($('#my-lineup-logos').find('.empty').length > 0){
						//_self.debug("$('#my-lineup-logos').find('.empty').length: "+$('#my-lineup-logos').find('.empty').length);
						_self.deactivate($this);
						_self.addToLineUp($this.attr('id'));
					} else {
						$('p#my-lineup-status').html('You can follow up to 6 teams. <b>To add another, remove a team first.</b>');
						alert("You can follow up to 6 teams. To add another, remove a team first.");
					}
				};
				
				return false;
			});
			
																			
											
			
			$('.my-lineup-logo').hover(function() {
					if($(this).hasClass('empty') == false) {
						$(this).find('a').toggle();
						$(this).addClass("hover");
					} else {
						$(this).addClass("emptyHover");
					}

				}, function() {
					if ($(this).hasClass('empty') == false) {
						$(this).find('a').toggle();
						$(this).removeClass("hover");
					} else {
						$(this).removeClass("emptyHover");
					}
			});
			
			$('.my-lineup-logo a').click(function() {
				_self.debug("my-lineup-logo a').click");
				var $par = $(this).parent()
				if ($par.hasClass('empty') == false) {
					$par.find('a').toggle();
					$par.removeClass("hover");
				} else {
					$par.removeClass("emptyHover");
				}

				var $this = $(this),
				  	$parent = $this.parent(),
					str = $parent.attr('id'),
					$id = str.split('my_');
					
				_self.debug("$id: "+$id);
				
				_self.activate($('#'+$id[1]));
				$this.toggle();
				
				return false;
			});

												  
			$('#league-selector').change(function() {
				var $oldLeague = _curLeague;
				_curLeague = $('#league-selector').val();
					$("#"+$oldLeague).toggleClass('hidden');
					$("#"+_curLeague).toggleClass('hidden');							   
			});

		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.myHeadlinesLineUp = function()
	{ 
		this.each(function() 
		{
			var $instance = new MyHeadlinesLineUp($(this));
			$(this).data("myHeadlinesLineUp", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function MyHeadlinesModule(root)
	{	
		// Private fields -------------------------------------------------------------------

		var _root = $('body'),
			_cookieCheck = null,
			_myLineUpCookie = "sn_myHeadlinesLineUp",
			_myPrefCookie = "sn_myHeadlinesPref",
			_myRegionCookie = "sn_region",
			_myRegion = null,
			_myPref = null,
			_myLineUp = new Array(),
			_myTeamTabs = $('.headlines-teams-listing').find('li'),
			_myHeadlinesWrapper = $('div.headlines-teams-news-listing .news-wrapper'),
			_myTeampageLinks = $('div.headlines-teams-news-listing .customize-headlines-holder'),
			_imgPath = "/assets/img/team_logos/scores/38x38/",
			_self = this,
			_opts = {
				debug: false
			};  

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			
			//check for channel cookie
			doCookieCheck: function (whichCookie)
			{
				var $myCookie = whichCookie;
				var c = $.cookies.get($myCookie);
				if (c != null) {
					if($myCookie = _myLineUpCookie){
						_myLineUp = c.split(',');
					} else if ($myCookie = _myPrefCookie){
						_myPref = c;	
					}
					return true;
				
				} else {
					return false;
				}
			},	
			
			//set user's channel cookie
			doCookieSet: function (whichCookie, whichValue)
			{
				var $tmp = window.location.href,
					$url = $tmp.split('/'),
					$loc = $url[2].split('.'),
					$dom = '.'+$loc[1]+'.'+$loc[2];
				 var cookieOptions = {
				    path: '/',
					domain: $dom,//'.pairsite.com', //'.sportsnet.ca',
				    hoursToLive: 90000,
				    secure: false
				  }
				var $cookie = whichCookie;
				var $value = whichValue;
				$.cookies.set($cookie, $value, cookieOptions);

			},
			
			initPrefCookieSet: function ()
			{
				var $prefTabLink = $('.tabs-container').find('a');
				
				$($prefTabLink).click(function() {
						var $this = $(this),
							$parent = $($this).parent('div');
							
						if($parent.hasClass('active')) {
							if($parent.hasClass('first')) {
								_myPref = "recent";				  
							} else {
								_myPref = "my_headlines";	
							}
							_self.doCookieSet(_myPrefCookie, _myPref);					  
						}
					});
				
				
			},
			
			activate: function(obj)
			{		
				var $el = obj,
					$old = $('.headlines-teams-listing').find('.selected-team'),
					$id = $el.attr('id');
				
				_self.debug("$old: " + $old.html());
				
				$old.removeClass('selected-team');	
				$el.addClass('selected-team');
				
				_myHeadlinesWrapper.each(function() {
					if($(this).hasClass('hidden') == false){
						$(this).toggleClass('hidden');
					};
				});
				_myTeampageLinks.each(function() {
					if($(this).hasClass('hidden') == false){
						$(this).toggleClass('hidden');
					};
				});
				
				$('#'+$id+'_headlines').removeClass('hidden');
				$('#'+$id+'_pagelink').removeClass('hidden');
			},
			
			initLineUp: function()
			{	
				for (var i=0; i<_myLineUp.length; i++) {
					var str = _myLineUp[i].split('|'),
						curLeague = str[0],
						curTeam = str[1],
						curSport = _self.getSport(curLeague),
						curNode = _myTeamTabs[i],
						curHeadlines = _myHeadlinesWrapper[i],
						curTeamlink = _myTeampageLinks[i],
						curImg = $(curNode).find('.my-module-logo'),
						curId = curLeague + '_' + curTeam;

					if ($.browser.msie6 == true) {
						curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.gif');
					} else {
						curImg.attr('src', _imgPath + curSport + '/' + curLeague + '/' + curTeam + '.png');
					};
					curImg.fadeIn('fast');
					$(curHeadlines).attr('id', curId+'_headlines');
					$(curTeamlink).attr('id', curId+'_pagelink');
					$(curNode).attr('id', curId);
					$(curNode).css('cursor', 'pointer');
					$(curNode).click(function() {
						_self.activate($(this));
					});
				}
			},
			
			getSport: function(league) 
			{
					var sport = null;
					
					switch(league){
						case "nhl":
							sport = "hockey";
							break;
						case "mlb":
							sport = "baseball";
							break;
						case "nfl": 
							sport = "football";
							break;
						case "cfl":
							sport = "football";
							break;
						default:
							sport = "basketball";		
							break;
							
					}
					return sport;
			},
			
			reloadPage: function () 
			{
				location.reload();
			},

			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						trace(str);
					} 
					catch (e) {
						alert(str);
					}
				}
			}
		});

		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	
			_prefCookieCheck = _self.doCookieCheck('sn_myHeadlinesPref');
			_lineupCookieCheck = _self.doCookieCheck('sn_myHeadlinesLineUp');
			_self.debug("_lineupCookieCheck: " + _lineupCookieCheck);
			_self.debug("_prefCookieCheck: " + _prefCookieCheck);
			
			if (_lineupCookieCheck == true){
				_self.initLineUp();	
			} else {
				_myLineUp = window.sn_HeadlinesLineUp.split(",");
				_self.initLineUp();
			};

			if (_prefCookieCheck == true){
				_self.initPrefCookieSet();	
			} else {
				_myPref = "recent";
				_self.initPrefCookieSet();
			};
			
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.myHeadlinesModule = function()
	{ 
		this.each(function() 
		{
			var $instance = new MyHeadlinesModule($(this));
			$(this).data("myHeadlinesModule", $instance);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function Scores(root, conf)
	{	
		// Private fields ------------------------------------------------------------------

		var _root = $(root),
			_self = this,
			_index = 0,
			_gameId = -1,
			_intervalId = 0
			;

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
		});

		// Private methods -----------------------------------------------------------------
		
		function initLayout()
		{
			if ($.browser.msie6)
				_root.addClass('ie6');
			else if ($.browser.msie7)
				_root.addClass('ie7');
			
			_gameId = /gameid-(\d+)/.exec(_root[0].className)[1];
			
			_intervalId = setInterval(function()
			{
				$.get(
					conf.updateUrl + '?id=' + _gameId + '&s=' + Math.random() + '&i=' + _index,
					{ i : _index },
					function(html)
					{
						_root.html(html);
						
						// clear querying interval when the game is marked final
						if (_root.find('.mini-scoreboard-header .periods').hasClass('final'))
						{
							clearInterval(_intervalId);
						}
						
						_index++;
					}
				);
			},
			opts.refresh
			);
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.scores = function(conf)
	{ 
		var opts = {
			refresh : 5000,
			updateUrl : '/ui_components/stats_modules/scores_render.php'
		};
		
		$.extend(opts, conf);		
		
		this.each(function() 
		{
			var $instance = new Scores($(this), opts);
			$(this).data("scores", $instance);	
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function ShowHideDetails(root, conf)
	{	
		// Private fields -------------------------------------------------------------------
		var _root = $(root),
			_trigger = _root.find('.details-link'),
			_target = _root.parent().find(".showhide-details-content"),
			_self = this,
			_opts = {
				debug: false,
				openString: _trigger.text(), //defaults
				closeString: _trigger.attr('name'),
				onOpen: null, //callbacks - passed directly to animation functions
				onClose: null
			};
		$.extend(_opts, conf);
			
		// Public methods ------------------------------------------------------------------


		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	
			_trigger.click(function() {
				if ($(this).hasClass('opened')) {
					_target.slideUp(200, _opts.onClose);
					$(this).toggleClass('opened');
					
						$(this).text(_opts.openString);
					
						
					
				}
				else {
					_target.slideDown(200, _opts.onOpen);
					$(this).toggleClass('opened');
					if(_trigger.attr('name') != undefined && _trigger.attr('name') != "") {
						$(this).text(_opts.closeString);
					} else {
						$(this).text(_opts.openString);
					}
				}
				return false;
			});
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.showHideDetails = function(conf)
	{ 
		var opts = {};
		$.extend(opts, conf);
		
		this.each(function() 
		{
			var $instance = new ShowHideDetails($(this), opts);
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function TrackerPoll(root, conf)
	{	
		// Private fields -------------------------------------------------------------------
		var _root = $(root),
			_optionTrigger = _root.find('.poll-option'),
			_viewTrigger = _root.find('.poll-view-results'),
			_voteTrigger = _root.find('.poll-vote-now'),
			_choicesTarget = _root.find('.poll-choices'),
			_resultsTarget = _root.find(".poll-results"), 
			_resultsTargetText = _root.find(".poll-results span"), 
			_self = this;

	
		// Public methods ------------------------------------------------------------------


		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	
			var fadeSpeed = 50;

			_optionTrigger.click(function() {
                $.ajax({
                    url: "/scrum/poll_vote.php",
                    cache: false,
                    data: "mode=tracker&response_id="+$(this).attr('href').substr(1),
                    success: function(html) {
                        _resultsTarget.html(html);

                        if ($.browser.msie6) { //fade messes up in ie6
                            _choicesTarget.hide();
                            _resultsTarget.show();
                        } else {
                            _choicesTarget.fadeOut(fadeSpeed, function(){
                                _resultsTarget.fadeIn(fadeSpeed);
                            });
                        }
                    }
                });

				return false;
			});
			
			_viewTrigger.click(function() {
                $.ajax({
                    url: "/scrum/poll_vote.php",
                    cache: false,
                    data: "mode=tracker&poll_id="+$(this).attr('href').substr(1),
                    success: function(html) {
                        _resultsTargetText.html(html);

                        if ($.browser.msie6) { //fade messes up in ie6
                            _choicesTarget.hide();
                            _resultsTarget.show();
                        } else {
                            _choicesTarget.fadeOut(fadeSpeed, function(){
                                _resultsTarget.fadeIn(fadeSpeed);
                            });
                        }
                    }
                });
				return false;
			});
			
			_voteTrigger.click(function() {
				if ($.browser.msie6) { //fade messes up in ie6
					_resultsTarget.hide();
					_choicesTarget.show();
				}
				else {
					_resultsTarget.fadeOut(fadeSpeed, function(){
						_choicesTarget.fadeIn(fadeSpeed);
					});
				}
				return false;
			});
			
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.trackerPoll = function()
	{ 
		var opts = {};
		$.extend(opts);
		
		this.each(function() 
		{
			var $instance = new TrackerPoll($(this));
		});
		
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function TabNav(root)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_self = this,
			_navTabs,
			_tabBottoms,
			_tabContentElems,
			_idx = 0,
			_old
			;
			
		// Public methods ------------------------------------------------------------------
		$.extend(_self, {
			onTabClick: function(tabElem) {
				var $tabElem = $(tabElem),
					_old = _idx;
					
				_idx = _navTabs.index($tabElem);
				
				_navTabs.eq(_old).toggleClass('on');
				_navTabs.eq(_idx).toggleClass('on');
				
				_tabBottoms.eq(_old).toggleClass('on');
				_tabBottoms.eq(_idx).toggleClass('on');
				
				_tabContentElems.eq(_old).toggleClass('hidden');
				_tabContentElems.eq(_idx).toggleClass('hidden');
				
				return false;
			}
		});
	
		// Private methods ------------------------------------------------------------------
		function init()
		{	
			//var $idx = 0;
			_navTabs = _root.find('td.tab-nav-option').click(function(){
				_self.onTabClick(this);
			});
			_navTabs.find("a").click(function(){
				_self.onTabClick($(this).closest("td.tab-nav-option"));
				return false;
			});
			_tabBottoms = _root.find('td.bottom-row');
			_tabContentElems = $('ul.tabs-featured');
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.tabNav = function()
	{
		
		this.each(function()
		{
			var $instance = new TabNav($(this));
		});
		
		return this;
	};
})(jQuery);
(function($)
{	
	// constructor
	function FollowTeamLink(root, conf)
	{	
		// Private fields -------------------------------------------------------------------
		var _root = $(root),
			_element = _root[0],
			_label = _root.find(".follow-team-label"),
			_self = this,
			_addLabel = "Follow this team",
			_addHelp = "Click to add this team to \"My Headlines\" line-up.",
			_removeLabel = "Stop following this team",
			_removeHelp = "Click to remove this team from \"My Headlines\" line-up.",
			_editLabel = "Edit \"My Headlines\" teams",
			_editHelp = "You are already following 6 teams. Click to go to \"My Headlines\" page and edit your line-up.",
			_myHeadlinesURL = "/myheadlines/",
			_cookieOptions = {
				    path: '/',
				    hoursToLive: 90000,
				    secure: false
				  },
			_opts = {
				debug: false,
				lineupId: null
			};
			$.extend(_opts, conf);

		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			reloadPage: function () 
			{
				location.reload();
			},
			getMyLineUp: function () 
			{
				var cookieVal = $.cookie("sn_myHeadlinesLineUp");
				var lineUp = cookieVal != null ? cookieVal : window.sn_HeadlinesLineUp;
				lineUp = lineUp.split(",");
				return lineUp;
			},
			updateDisplay: function ()
			{
				//if the my headlines module is on the page, reload - otherwise, just update the link
				var moduleIsPresent = $("div.my-teams-headlines").length > 0;
				_self.debug("moduleIsPresent: " + moduleIsPresent);
				if (moduleIsPresent) {
					_self.reloadPage();
				}
				else {
					_self.updateLink();
				}
			},
			removeTeam: function () 
			{
				_self.debug("removeTeam---");
				_self.debug("b4: " + $.cookie("sn_myHeadlinesLineUp"));
				_myLineUp = $.grep(_myLineUp, function(value){
					return value != _opts.lineupId;
				});
				$.cookies.set("sn_myHeadlinesLineUp", _myLineUp, _cookieOptions);
				_self.debug("aft: " + $.cookie("sn_myHeadlinesLineUp"));
				
				_self.updateDisplay();
			},
			addTeam: function () 
			{
				_self.debug("addTeam---");
				_self.debug("b4: " + $.cookie("sn_myHeadlinesLineUp"));
				_myLineUp.push(_opts.lineupId);
				
				$.cookies.set("sn_myHeadlinesLineUp", _myLineUp, _cookieOptions);
				
				_self.debug("aft: " + $.cookie("sn_myHeadlinesLineUp"));
				
				_self.updateDisplay();
			},
			updateLink: function () 
			{
				_root.unbind(); //remove any existing event handlers
				
				var teamIsInLineup = $.inArray(_opts.lineupId, _myLineUp) != -1;
				if (teamIsInLineup) {
					_label.html(_removeLabel);
					_root.attr('title', _removeHelp);
					_root.click(function(){
						_self.removeTeam();
						return false;
					});
				}
				else {
					var hasSpace = _myLineUp.length < 6;
					if (hasSpace) {
						_label.html(_addLabel);
						_root.attr('title', _addHelp);
						_root.click(function(){
							_self.addTeam();
							return false;
						});
					}
					else {
						_label.html(_editLabel);
						_root.attr('title', _editHelp);
						_root.attr('href', _myHeadlinesURL);
					}
				}
			},
			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						trace(str);
					} 
					catch (e) {
						alert(str);
					}
				}
			}
		});

		// Private methods ----------------------------------------------------------------
		function initLayout()
		{
			_myLineUp = _self.getMyLineUp();
			_self.updateLink();
			_root.show();
			
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
		

	};

	// jQuery plugin implementation
	$.fn.followTeamLink = function(opts)
	{ 
		this.each(function() 
		{
			new FollowTeamLink($(this), opts);
		});
	};
})(jQuery);
(function($)
{	
	// constructor
	function NewsArchiveFilter(root, conf)
	{	

		// Private fields -------------------------------------------------------------------

		var _page = $('body'),
			_root = $(root),
			_feedOptions = _root.find('a'),
			_contentHolder = _page.find('.content-listing'),
			$tmp = $(_root.find('.news-archive-sports a')).attr("id"),
			$t = $tmp.split("|"),
			_leagueName = $t[1],
			_curStories = new Array(),
			_filteredStories = new Array(),
			_self = this,
			_opts = {
				debug: false
			}; 
			 
		$.extend(_opts, conf);
		
		// Public methods ------------------------------------------------------------------
		
		$.extend(_self, {
			
			getFeed: function(type, feed)
			{
				var $feed = feed + "/xml/index.xml",
					$sport = _self.getSport(_leagueName);

				if (type == "team")
				{
					$feed = "news_"+feed + "/xml/index.xml";
				};
				if ($sport == "football") {
					var $path = $sport + "/" + _leagueName + "/"; 
				}
				else {
					var $path = $sport + "/";
				};	
				$.ajax({
					type: "GET",
					url: $path + $feed,
					dataType: "xml",
					success: function(xml){
						_self.killStories();
						_self.buildStories(xml);
					},
					error: function(){
						_self.doXMLError();
					}
				});
			},

			getSport: function(league) 
			{
					var sport = null;
					
					switch(league){
						case "nhl":
							sport = "hockey";
							break;
						case "mlb":
							sport = "baseball";
							break;
						case "nfl": 
							sport = "football";
							break;
						case "cfl":
							sport = "football";
							break;
						default:
							sport = "basketball";		
							break;
					}
					return sport;
			},
			
			buildStories: function(xml)
			{
				var $xmlObj = $(xml),
					_storyArray = $xmlObj.find('item'),
					_sectionDate = null;

				for(var i=0; i < _storyArray.length; i++)
				{
					var curStory = _storyArray[i],
						curDate = $($(curStory).find('citation')).attr('date'),
						curURL = $(curStory).attr('url'),
						curComment = $(curStory).attr('comments'),
						curCommentURL = $(curStory).attr('commentsURL'),
						curVideo = $(curStory).attr('hasVideo'),
						curHeadline = $($(curStory).find('headline')).text(),
						curSummary = $($(curStory).find('summary')).text()
						id = i;

					if(curDate == _sectionDate)
					{
						_self.createArticle(curURL, curComment, curCommentURL, curVideo, curHeadline, curSummary, id);
					} else {
						_sectionDate = curDate;
						_self.createDateSection(_sectionDate);
						_self.createArticle(curURL, curComment, curCommentURL, curVideo, curHeadline, curSummary, id);
					};
				}
				_contentHolder.children('li:last').addClass('last');
				_self.showStories();	
			},
			
			createDateSection: function(date)
			{
				var $tmp = date.split(" "),
					$month = $tmp[0],
					d = $tmp[1],
					dt = d.split(","),
					$day = dt[0],
					$year = $tmp[2],
					$section = "<li class='date-section'><div class='press-date'><span class='month'>"+$month+"</span><span class='day'>"+$day+"</span><span class='year'>"+$year+"</span></div><div class='press-items'><ul class='press-link-list'></ul></div></li>";
				
				_contentHolder.append($section); 
			},
			
			createArticle: function(url, comments, commentsURL, hasVideo, headline, summary, id)
			{
				var $section = _contentHolder.find('li.date-section:last');
					$articleWrapper = $section.find('ul.press-link-list'),
					$url = url,
					$comments = comments,
					$commentsURL = commentsURL,
					$hasVideo = hasVideo,
					$head = headline,
					$sum = summary,
					$id = id,
					$content = "<li id='"+$id+"'><a href='"+$url+"'>"+$head+"</a><span class='comment-balloon'><a href='"+$commentsURL+"'>"+$comments+"</a></span><span class='comment-video'><a href='"+$url+"'><img src='/assets/img/comment_video.gif'></a></span><p class='list-desc ellipsis multiline'>"+$sum+"</p></li>";
					
				$articleWrapper.append($content);
				if($comments <= 0 || $comments == undefined){
					$("li#"+$id+" span.comment-balloon").hide();
				}	
				if($hasVideo == "false" || $hasVideo == undefined){
					$("li#"+$id+" span.comment-video").hide();
				}
			},
			
			killStories: function()
			{
				_contentHolder.empty();
			},
			
			hideStories: function()
			{
				_contentHolder.hide();
				_contentHolder.parent().find('.error-content').hide();
				_contentHolder.parent().find('.updating-content').show();
			},
			
			showStories: function()
			{
				_contentHolder.parent().find('.updating-content').hide();
				_contentHolder.fadeIn();
			},
			
			doXMLError: function()
			{
				_contentHolder.parent().find('.updating-content').hide();
				_contentHolder.parent().find('.error-content').show();
			},
			
			debug: function(str)
			{
				if (_opts.debug == true) {
					try {
						trace(str);
					} 
					catch (e) {
						alert(str);
					}
				}
			}
		});

		// Private methods ----------------------------------------------------------------
		function initLayout()
		{	
			_contentHolder.parent().prepend('<div class="updating-content">Updating Content</div>');		
			_contentHolder.parent().prepend('<div class="error-content">The news feed you have chosen is currently unavailable.  Please select a different feed, or try again later.</div>');		
			_contentHolder.parent().find('.updating-content').hide();
			_contentHolder.parent().find('.error-content').hide();
			_self.hideStories();
			_self.getFeed("league", _leagueName);
			
			_feedOptions.click(function() 
			{
				var $this = $(this),
					$id = $this.attr('id'),
					tmp = $id.split('|'),
					$league = tmp[0],
					$feed = tmp[1];

				setTimeout(function(){
					_page.find('.default').text($this.text());	
					_self.hideStories();
					_self.getFeed($league, $feed);}, 750);
													
				return false;
			})
		};

		// Initialization ------------------------------------------------------------------
		
		initLayout();
	};

	// jQuery plugin implementation
	$.fn.newsArchiveFilter = function(conf)
	{ 
		var opts = {};
		$.extend(opts, conf);
		
		this.each(function() 
		{
			var $instance = new NewsArchiveFilter($(this), opts);
		});
		return this; 
	};
})(jQuery);
(function($)
{	
	// constructor
	function DataLayoutManager(root)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_domElement = _root[0],
			_containerDiv,
			_contentDiv,
			_bodyDiv,
			_rightColDiv,
			_self = this,
			_opts = {
				debug: false
			}
			;
	
		// Public methods ------------------------------------------------------------------
		$.extend(_self, {
			contentIsTooWide: function()
			{
				var myWidth = _root.width();
				var tableWidth = _root.find("table.stats").width();
				debug("myWidth: " + myWidth);
				debug("tableWidth: " + tableWidth);
				
				var isTooWide = tableWidth > myWidth;
				debug("isTooWide: " + isTooWide);
				return isTooWide;
			},
			initRightColumn: function()
			{
				_rightColDiv = _contentDiv.find("div.column.span-5.last");
				_rightColDiv.absolutize();
			},
			placeRightColumn: function()
			{
				var targetLeft = _containerDiv.offset().left + _containerDiv.width() + 1; //1 accounts for the border (not 2 since we want to overlap the right edge border)
				debug(" targetLeft: " + targetLeft);
				_rightColDiv.css({
					'left': targetLeft+"px",
					'border-top': "1px solid #999999",
					'border-right': "1px solid #999999",
					'border-bottom': "1px solid #999999",
					'background-color': "#FFFFFF",
					'padding-top': "15px"
				});
			},
			expandBody: function()
			{
				_bodyDiv = _contentDiv.find("div.column.span-10:first");
				//make the main div span all columns
				_bodyDiv.removeClass("span-10");
				_bodyDiv.addClass("span-15 last");
				//make all the children span all columns
				_bodyDiv.find("div.column.span-10").each(function(){
					_this = $(this);
					_this.removeClass("span-10");
					_this.addClass("span-15");
				});
			}
		});
	
		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					trace(str);
				} 
				catch (e) {
					alert(str);
				}
			}
		};
			
		// generic binding function
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);
		};
	
		function init()
		{	
			if (_self.contentIsTooWide()) {
				_containerDiv = $("body > div.container:first");
				_contentDiv = $("div.container > #content");
				
				_self.initRightColumn();
				_self.placeRightColumn();
				_self.expandBody();
					
				$(window).resize(function(){
					_self.placeRightColumn();
				});
			}
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.dataLayoutManager = function()
	{
		this.each(function()
		{
			var $instance = new DataLayoutManager($(this));
		});
		
		return this;
	};
	
    jQuery.fn.absolutize = function(rebase){
		return this.each(function() {
			var el = $(this);
			var pos = el.position();
			el.css({ position: "absolute",
			marginLeft: 0, marginTop: 0,
			top: pos.top, left: pos.left });
			if (rebase)
				el.remove().appendTo("body");
		});
    };
	
})(jQuery);
//strings
function stripTags(string){
	return string.replace(/<\/?[^>]+>/gi, '');
}

//twitter module
function retweetThis() {
	var tweetElem = $("ul.twitter");
	var twitterUrl = tweetElem.find("li.feeds p.name a").attr("href");
	var src = "@" + (twitterUrl.substr(twitterUrl.indexOf("twitter.com/") + 12).split("/")[0]) + " ";
	//var src = "@" + stripTags(tweetElem.find("span#twitterSource").html()) + " ";
	var tweet = stripTags(tweetElem.find("p#twitterTweet").html());
	var tURL = "http://twitter.com/home?status=" + encodeURIComponent(src + tweet);
	var w = window.open(tURL, "twitterWindow");
	return false;
}
var addthis_pub             = 'sportsnet',
	addthis_logo            = '/assets/img/share_this/sportsnet_logo_for_popup.gif',
	addthis_logo_background = 'FFFFFF',
	addthis_logo_color      = '000000',
	addthis_brand           = 'Sportsnet.ca',
	addthis_options         = 'email, facebook, delicious, myspace, favorites, google, myweb, live, digg, more';

var _atu="undefined",_euc=encodeURIComponent,_atc={samp:0.05,addr:-1};if(typeof(addthis_conf)===_atu){var addthis_conf={};}
for(i in addthis_conf){_atc[i]=addthis_conf[i];}
if(typeof(_ate)===_atu){var _ate={ab:"-",clck:1,show:1,samp:_atc.samp-Math.random(),scnt:1,seqn:1,inst:1,wait:500,tmot:null,cvt:[],svt:[],sttm:new Date().getTime(),max:268435455,pix:"tev",sid:0,sub:typeof(at_sub)!==_atu,uid:null,wid:"AT-"+(typeof(addthis_pub)!==_atu?_euc(addthis_pub):"unknown"),swf:"http://bin.clearspring.com/at/v/1/button1.swf",evu:"http://e1.clearspring.com/at/",mun:function(s){var mv=291;for(var i=0;i<s.length;i++){mv=(mv*(s.charCodeAt(i)+i)+3)&1048575;}
return(mv&16777215).toString(32);},off:function(){return Math.floor((new Date().getTime()-_ate.sttm)/100).toString(16);},ran:function(){return Math.floor(Math.random()*4294967295).toString(36);},img:function(i,a){if(typeof(at_sub)===_atu){new Image().src="http://s7.addthis.com/cs/1/"+i+".png?"+_ate.ran()+"=1&"+(a||"");}},cuid:function(){return(_ate.sttm&_ate.max).toString(16)+(Math.floor(Math.random()*_ate.max)).toString(16);},ssid:function(){if(_ate.sid===0){_ate.sid=_ate.cuid();}
return _ate.sid;},sev:function(id,_7){_ate.pix="sev-"+(typeof(id)!=="number"?_euc(id):id);_ate.svt.push(id+";"+_ate.off());if(_7===1){_ate.xmi(true);}else{_ate.sxm(true);}},cev:function(k,v){_ate.pix="cev-"+_euc(k);_ate.cvt.push(_euc(k)+"="+_euc(v)+";"+_ate.off());_ate.sxm(true);},sxm:function(b){if(_ate.tmot!==null){clearTimeout(_ate.tmot);}
if(b){_ate.tmot=_ate.sto("_ate.xmi(false)",_ate.wait);}},sto:function(c,t){return setTimeout(c,t);},sta:function(){var a=_ate;return a.wid+"/-/"+a.ab+"/"+a.ssid()+"/"+(a.seqn++)+(a.uid!==null?"/"+a.uid:"");},xmi:function(_e){var a=_ate;if(!a.uid){a.dck("X"+a.cuid());}
if(a.cvt.length+a.svt.length>0){a.sxm(false);if(a.seqn===1){a.cev("pin",a.inst);}
var url=a.evu+a.pix+"-"+a.ran()+".png?ev="+_ate.sta()+"&se="+a.svt.join(",")+"&ce="+a.cvt.join(",");a.cvt=[];a.svt=[];if(_e){var d=document,i=d.createElement("iframe");i.id="_atf";i.src=url;_ate.opp(i.style);d.body.appendChild(i);i=d.getElementById("_atf");}else{new Image().src=url;}}},opp:function(st){st.width="1px";st.height="1px";st.position="absolute";st.zIndex=100000;},lod:function(){var a=_ate;if(a.samp>=0&&!a.sub){a.sev("20");a.cev("plo",1/_atc.samp);}
var d=document,n=navigator,u=n.userAgent.toLowerCase(),b={msi:/msie/.test(u)&&!(/opera/.test(u))};if(!_atc.noswf&&a.uid==null&&a.swf!==null){var _19=function(o,n,v){var c=d.createElement("param");c.name=n;c.value=v;o.appendChild(c);};var ato=d.createElement("object");a.opp(ato.style);ato.id="_atff";if(b.msi){ato.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";_19(ato,"movie",a.swf);}else{ato.data=a.swf;ato.quality="high";ato.type="application/x-shockwave-flash";}
_19(ato,"wmode","transparent");_19(ato,"allowScriptAccess","always");d.body.insertBefore(ato,d.body.firstChild);if(b.msi){ato.outerHTML+=" ";}}},unl:function(){var a=_ate;if(a.samp>=0&&!a.sub){a.sev("21",1);a.cev("pun",1/_atc.samp);}
return true;},dck:function(c){_ate.uid=c;document.cookie="_csuid="+c+"; expires=Wed, 04 Oct 2028 03:19:53 GMT; path=/";},asetup:function(x){var a=_ate;try{if(x!==null&&x!==_atu){a.dck(x);}}
catch(e){}
return x;}};(function(){var a=_ate,d=document,w=window,wa=w.addEventListener,we=w.attachEvent;if(wa){wa("load",a.lod,false);wa("unload",a.unl,false);}else{if(we){we("onload",a.lod);we("onunload",a.unl);}else{w.onload=a.lod;w.onunload=a.unl;}}
var ck=d.cookie.split(";");for(var i=0;i<ck.length;i++){var c=ck[i];var x=c.indexOf("_csuid=");if(x>=0){_ate.uid=c.substring(x+7);}}})();}else{_ate.inst++;}
if(typeof _atw===_atu){var _atw={addr:_atc.addr-Math.random(),addt:_atc.addt>=0?_atc.addt:Math.floor(4*Math.random()),host:"http://s7.addthis.com/",serv:"http://s7.addthis.com/services/",path:"http://s7.addthis.com/select/",list:{"ask":["Ask"],"delicious":["Del.icio.us"],"digg":["Digg"],"email":["Email"],"favorites":["Favorites"],"facebook":["Facebook"],"fark":["Fark"],"furl":["Furl"],"google":["Google"],"live":["Live"],"myspace":["MySpace"],"myweb":["Yahoo MyWeb","yahoo-myweb"],"newsvine":["Newsvine"],"reddit":["Reddit"],"sk*rt":["Sk*rt","skrt"],"slashdot":["Slashdot"],"stumbleupon":["StumbleUpon","su"],"stylehive":["Stylehive"],"tailrank":["Tailrank","tailrank2"],"technorati":["Technorati"],"thisnext":["ThisNext"],"twitter":["Twitter"],"ballhype":["BallHype"],"yardbarker":["Yardbarker"],"kaboodle":["Kaboodle"],"more":["More ..."]},div:null,pub:(typeof(addthis_pub)!==_atu?_euc(addthis_pub):""),get:function(id){return document.getElementById(id);},xwa:function(){if(_atw.cwa!==null){clearTimeout(_atw.cwa);}},cwa:null,ost:false,did:"addthis_dropdown15",sli:function(_2d){for(var i=0;i<_atw.sin.length;i++){var sio=_atw.sin[i];if(sio.pos>=sio.end){_atw.sin.splice(i,1);}else{sio.pos+=sio.inc;sio.obj.style.height=sio.pos+"px";}}
if(_atw.sin.length>0){_ate.sto("_atw.sli("+_2d+")",_2d);}},sla:function(obj,end,_32,inc,_34){_atw.sin.push({"obj":obj,"pos":0,"end":end,"inc":inc});_ate.sto("_atw.sli("+_32+")",_34);},sin:[],clo:function(){var _35=_atw.get(_atw.did);if(_35){_35.style.display="none";}
var e=document.getElementsByTagName("embed");if(e&&addthis_hide_embed){for(i=0;i<e.length;i++){if(e[i].addthis_hidden){e[i].style.visibility="visible";}}}
return false;},cof:function(obj){obj.style.color="#000000";if(obj.value==" email address"){obj.value="";}},sho:function(_38){var _39=_atw.get("at_share"),_3a=_atw.get("at_email"),_3b=_atw.get("at_caption"),_3c=_atw.get("at_success");_39.style.display="none";_3a.style.display="none";_3c.innerHTML="";if(_38=="share"||_38==""){_39.style.display="block";_3b.innerHTML=addthis_caption_share;if(_ate.show-->0){_ate.sev("40");_ate.cev("sho","share");}}else{_3a.style.display="block";_3b.innerHTML=addthis_caption_email;if(_ate.show-->0){_ate.sev("40");_ate.cev("sho","email");}}},uadd:function(svc){return"pub="+_atw.pub+"&s="+svc+"&url="+_euc(addthis_url)+"&title="+_euc(addthis_title)+"&logo="+_euc(addthis_logo)+"&logobg="+addthis_logo_background+"&logocolor="+addthis_logo_color+"&ate="+_ate.sta()+"&adt="+_atw.addt;},genurl:function(svc){return"http://www.addthis.com/bookmark.php?v=15&winname=addthis&"+_atw.uadd(svc);},cumpos:function(a){var b=0,c=0;do{b+=a.offsetTop||0;c+=a.offsetLeft||0;a=a.offsetParent;}while(a);return[c,b];},wsize:function(){var w=window,d=document,de=d.documentElement,db=d.body;if(typeof(w.innerWidth)=="number"){return[w.innerWidth,w.innerHeight];}else{if(de&&(de.clientWidth||de.clientHeight)){return[de.clientWidth,de.clientHeight];}else{if(db&&(db.clientWidth||db.clientHeight)){return[db.clientWidth,db.clientHeight];}else{return[0,0];}}}},spos:function(){var w=window,d=document,de=d.documentElement,db=d.body;if(typeof(w.pageYOffset)=="number"){return[w.pageXOffset,w.pageYOffset];}else{if(db&&(db.scrollLeft||db.scrollTop)){return[db.scrollLeft,db.scrollTop];}else{if(de&&(de.scrollLeft||de.scrollTop)){return[de.scrollLeft,de.scrollTop];}else{return[0,0];}}}}};function addthis_open(elt,_4b,_4c,_4d){var d=document;if(_atw.div){d.body.insertBefore(_atw.div,d.body.firstChild);_atw.div.style.zIndex=1000000;_atw.div=null;}
_atw.xwa();addthis_url=_4c;addthis_title=_4d;if(addthis_url===""||addthis_url==="[URL]"){addthis_url=location.href;}
if(addthis_title===""||addthis_title==="[TITLE]"){addthis_title=d.title;}
var _4f=16;var _50=elt.getElementsByTagName("img");if(_50&&_50[0]){elt=_50[0];_4f=0;}
_atw.sho(_4b);var _51=_atw.cumpos(elt),_52=_51[0]+addthis_offset_left,_53=_51[1]+_4f+1+addthis_offset_top,_54=_atw.wsize(),_55=_atw.spos(),_56=_atw.get(_atw.did),_57=_56.style,dir=0;_57.display="block";var _59=_56.clientWidth,_5a=_56.clientHeight;if(_52-_55[0]+_59+20>_54[0]){_52=_52-_59+50;dir++;}
if(_53-_55[1]+_5a+elt.clientHeight+20>_54[1]){_53=_53-_5a-20;dir+=2;}
_ate.cev("dir",dir);_57.left=_52+"px";_57.top=(_53+elt.clientHeight)+"px";if(addthis_hide_embed){var _5b=_52+_59,_5c=_53+_5a,e=d.getElementsByTagName("embed"),_5e=0,_5f=0,_60=0;for(i=0;i<e.length;i++){_5e=_atw.cumpos(e[i]);_5f=_5e[0];_60=_5e[1];if(_52<_5f+e[i].clientWidth&&_53<_60+e[i].clientHeight){if(_5b>_5f&&_5c>_60){if(e[i].style.visibility!="hidden"){e[i].addthis_hidden=true;e[i].style.visibility="hidden";}}}}}
if(!_atw.ost){if(_atw.addr>=0){_ate.ab=_atw.addt;var nl=2;switch(_ate.ab){case 3:nl=65;break;}
var _62=nl,pxl=_62*23,atf=_atw.get("at_plus");if(_62>3){pxl=_62;}
if(_62>250){_56.style.width="310px";}else{if(_62>50&&_62<100){_56.style.width="240px";}}
atf.src="http://www.addthis.com/ads.php?r="+_ate.ran()+"&url="+_euc(addthis_url)+"&ate="+_ate.sta()+"&adt="+_atw.addt+"&pub="+_atw.pub+"&lnz="+_62;switch(_ate.ab){case 0:_atw.sla(atf,pxl,5,pxl/16,2000);break;case 1:_atw.sla(atf,pxl,5,pxl/16,0);break;default:_atw.sla(atf,pxl,5,pxl,0);break;}}else{_ate.ab="~";}
_atw.ost=true;}
return false;}
function addthis_close(){_atw.cwa=_ate.sto("_atw.clo()",500);}
function addthis_sendto(s){trkCustLnk('','AddThis','');if(s==="email"){_atw.sho(s);return false;}
_atw.clo();if(s==="favorites"){if(document.all){window.external.AddFavorite(addthis_url,addthis_title);}else{window.sidebar.addPanel(addthis_title,addthis_url,"");}
return false;}
if(s==="stumbleupon"){s="su";}
if(s==="sk*rt"){s="skrt";}
window.open(_atw.genurl(s),"addthis","scrollbars=yes,menubar=no,width=625,height=610,resizable=yes,toolbar=no,location=no,status=no");if(s){_ate.cev("sct",_ate.scnt++);}else{_ate.cev("clk",_ate.clck++);}
return false;}
function addthis_send(){var _66=_atw.get("at_from"),_67=_atw.get("at_to"),_68=_atw.get("at_success"),_69=_atw.get("at_msg");if(_66.value.indexOf("@")<0||_67.value.indexOf("@")<0||_66.value.indexOf(".")<0||_67.value.indexOf(".")<0){alert("Please enter a valid email address!");return;}
new Image().src="http://www.addthis.com/tellfriend.php?&fromname=aaa&fromemail="+_euc(_66.value)+"&tofriend="+_euc(_67.value)+"&note="+_euc(_69.value)+"&"+_atw.uadd("e");_68.innerHTML="Message Sent!";_atw.cwa=_ate.sto("_atw.clo()",1200);return false;}
(function(){try{var mn=_ate.mun(_atw.pub);var ma=["6jb4","3j1d","v1me","gu83","uefc","fq1j","r5l7","ftho","gdq9","717h","24b7","d0en","ads7","m9b4","n0lq","42c3","p5mp","7hbi","f0g6","7v98","mv86","d0ns","9a8a","64gg","jogl","cehp","mu2r","6h7h","sntb","94ds","n1fv","3a2i","3end","l42s","a9j","q3dj","s150","di3s","3nu5","sk74","e39d","mkvj","482d","kfej","nlcv","eroi","m6ee","rvaa","9nis","ef6b","g00q","b4hp","kbpq","bm4l","f7iu","e5gb","1sbj","rk0a","ck86","1etp","26sr","fivt","3v95","foqq","vtmj","canb","bchv","ku35","q4p9","gdkt","gng8","mdb9","ejjg","27k9","30mf","nene","smmm","q204","83ot","6kbr","df1o","1q0j","nh32","ebso","d6t5","f2dp","3sqp","i4cs","6k7b","a1pv","ki2l","1f7","d6lv","u7r5","9t0e","5h0l","j8kn","7akj","9tj","jmu3","1ir1"];for(var i in ma){if(ma[i]===mn){_atw.addr=-1;break;}}
try{if(location.href.toString().indexOf("http")!=0){_atw.addr=-1;}}
catch(e){}
if(typeof addthis_caption===_atu){addthis_caption="Bookmark &amp; Share";}
if(typeof addthis_brand===_atu){addthis_brand="";}
if(typeof addthis_logo===_atu){addthis_logo="";}
if(typeof addthis_logo_background===_atu){addthis_logo_background="";}
if(typeof addthis_logo_color===_atu){addthis_logo_color="";}
if(typeof addthis_options===_atu){addthis_options="favorites, digg, delicious, google, myspace, facebook, reddit, newsvine, live, more";}
if(typeof addthis_offset_top!=="number"){addthis_offset_top=0;}
if(typeof addthis_offset_left!=="number"){addthis_offset_left=0;}
if(typeof addthis_caption_share===_atu){addthis_caption_share="Bookmark &amp; Share";}
if(typeof addthis_caption_email===_atu){addthis_caption_email="Email a Friend";}
if(typeof addthis_css===_atu){addthis_css=_atw.host+"css/152/widget-02.css";}
if(typeof addthis_hide_embed===_atu){addthis_hide_embed=true;}
addthis_options=addthis_options.replace(/\s/g,"");var d=document,s="<div id=\""+_atw.did+"\" onmouseover=\"_atw.xwa()\" onmouseout=\"addthis_close()\" style=\"z-index:1000000;position:absolute;display:none\">";s+="<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" style=\"background-color:#EEEEEE;height:18px\">";s+="<tr><td style=\"font-size:12px;color:#666666;padding-left:3px\"><span id=\"at_caption\">Bookmark&nbsp;&amp;&nbsp;Share</span></td><td align=\"right\" style=\"font-size:9px;color:#666666;padding-right:3px\">"+addthis_brand+"</td></tr>";s+="</table>";var _6f=false;s+="<div id=\"at_share\">";s+="<table id=\"addthis_services\" width=\"100%\" cellpadding=\"0\" style=\"font-family:Verdana, Arial;font-size:11px\">";s+="<tr><td colspan=\"2\" style=\"height:0px\"></td></tr>";var _70=addthis_options.split(",");for(var i=0;i<_70.length;i++){var _71=_70[i],_72=_atw.list;if(_71 in _72){if(!_6f){s+="<tr>";}
s+="<td width=\"50%\" style=\"height:19px\"><a href=\"/\" onclick=\"return addthis_sendto('"+_71+"');\"><span class=\"at_tiles at_tile_"+(_72[_71][1]||_71)+"\"></span>&nbsp;"+_72[_71][0]+"</a></td>";if(_6f){s+="</tr>";}
_6f=!_6f;}}
if(_6f){s+="<td></td></tr>";}
s+="<tr><td colspan=\"2\" style=\"height:2px\"></td></tr>";s+="</table>";s+="</div>\n";s+="<div id=\"at_email\" style=\"display:none;font-size:11px;padding-left:20px;padding-top:6px\">";s+="<table border=\"0\">";var i1="<tr><td style=\"font-size:12px\"",i2="style=\"width:130px;height:18px;font-size:11px;font-family:Arial;color:#999999\" value=\" email address\" onfocus=\"_atw.cof(this)\" /></td></tr>";s+=i1+">To:</td><td><input id=\"at_to\" type=\"text\" "+i2;s+=i1+">From:</td><td><input id=\"at_from\" type=\"text\" "+i2;s+=i1+" valign=\"top\">Note:</td><td><textarea id=\"at_msg\" style=\"width:130px;height:36px;font-size:11px;font-family:Arial;\"/></textarea></td></tr>";s+="<tr><td colspan=\"2\" align=\"right\"><span id=\"at_success\" style=\"font-size:10px;color:#777777;\"></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"button\" value=\"Send\" onclick=\"return addthis_send()\" style=\"font-size:9px\"/></td></tr>";s+="</table>";s+="</div>\n";if(_atw.addr>=0){s+="<iframe style=\"border-top:1px solid #eeeeee;width:100%;height:0px\" id=\"at_plus\" src=\"\" scrolling=\"no\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\"></iframe>";}
s+="<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"background-color:#EEEEEE\">";s+="<tr><td colspan=\"2\" align=\"right\" style=\"padding:0px;padding-right:10px;height:11px\"><a href=\"http://www.addthis.com\" target=\"_blank\" style=\"height:6px;padding:0px\"><img src=\""+_atw.serv+"addthis-mini.gif?CXNID=2000001.5215456080540439072NXC\" border=\"0\" style=\"padding:0px;width:50px;height:9px\" alt=\"\" /></a></td></tr>";s+="</table>\n";s+="</div>\n";var l=d.createElement("link");l.rel="stylesheet";l.type="text/css";l.href=addthis_css;l.media="all";d.lastChild.firstChild.appendChild(l);_atw.div=d.createElement("div");_atw.div.innerHTML=s;}
catch(e){}})();}

/** Drag and Drop **/
var DEFAULT_RANKING_FIELD = '<span class="instructions">Drag and Drop</span>';
$(document).ready(function(){
	$(".rank .block").each( function (i) {
		$(this).html($(this).html().toString().replace(/<a /gi, '<a target="_blank" '));
	});
	$(".rank .block").draggable({
		cursorAt: { top: '1', left:  '2' }, 
		cursor: 'none', 
		helper: function() { return $(this).find(".meta").clone().removeClass("meta").addClass("label").css("cursor", "none").css("font-weight", "bold").css("font-size", "12px").css("padding", "5px").css("width", $(this).css("width")).css("z-index", "10000").css("white-space", "nowrap"); }
	}); 
	$(".drop").droppable({
		accept: function(draggable) { return (($(draggable).is('.block')) && ($(this).closest(".rank").attr("id") == $(draggable).closest(".rank").attr("id"))); }, 
		activeClass: 'dropactive',
		hoverClass: 'drophover',
		drop: function(ev, ui) {
			$(this).closest(".rank-answers").each(
					function (i) { 
							$(this).find(".drop").each( function (i) {
									if ($(this).find(".label") && $(this).find(".label").attr("id") == $(ui.draggable).find(".meta").attr("id")) {
										$(this).html(DEFAULT_RANKING_FIELD);
									}
							});
					});
			$(this).empty();
			$(this).append($(ui.draggable).find(".meta").clone().removeClass("meta").addClass("label"));
		}
	});
	$(".rank .block").dblclick(function () {
		var url = $(this).find(".img").attr("value");
		var nameTag = $(this).find(".meta").html();
		
		if (url) {
			var imgTag = "<img src='" + url + "' alt='" + name + "' />";
			$("#screener").remove();
			$("<div id='screener' onclick='$(this).html(\"\"); $(this).remove();'><div class='sidead leftad'></div><div class='screenshot'>" + imgTag + "<div class='screenname'>" + nameTag + "</div></div><div class='sidead rightad'></div><div class='screenbg'/></div>").appendTo("body");
			$("#screener .screenbg").css("z-index", "99").css("opacity", "0.75").css("background-color", "#000000");
			$("#screener").css("overflow", "auto");
			$("#screener .screenshot").css("z-index", "100").css("position", "relative").css("overflow", "hidden").css("display", "inline");
			$("#screener .sidead").css("z-index", "100").css("position", "relative").css("overflow", "hidden").css("display", "inline");
			
			var imgPreloader = new Image();
			imgPreloader.onload = function() {
				var margin = 4;
				var nameheight = 20;
				var w = window.innerWidth || self.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth;
				var h = window.innerHeight || self.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight;
				var imageWidth = (imgPreloader.width < w?(w - imgPreloader.width) / 2:0);
				var imageHeight = (imgPreloader.height < h?(h - imgPreloader.height) / 2:0);
				var bestwidthpx = Math.max(w, imgPreloader.width + margin * 2);
				var bestheightpx = Math.max(h, imgPreloader.height + margin * 2 + nameheight + margin * 2);
				var adwidthpx = '160';
				var adheightpx = '600';
				
				fixPositionFixed(fixWidthHeight($("#screener"), bestwidthpx, bestheightpx), true);
				fixPositionFixed(fixWidthHeight($("#screener .screenbg"), bestwidthpx , bestheightpx), false);
				$("#screener .screenshot").css("margin", imageHeight + "px" + " 0px 0px " + imageWidth + "px").css("display", "block");
				$("#screener .screenname").css("height", nameheight + "px").css("background-color", "#FFFFFF").css("padding", margin + "px").css("font-weight", "bold").css("width", imgPreloader.width + "px").css("text-align", "center");
				$("#screener .screenshot img").css("border", margin + "px solid #FFFFFF");
				
				fixPositionFixed($("#screener .sidead").css("width", adwidthpx + "px").css("height", adheightpx + "px").css("float", "left"), false);
				$("#screener .leftad").css("top", imageHeight + "px").css("left", (imageWidth - adwidthpx - margin) + "px").css("text-align", "right");
				$("#screener .rightad").css("top", imageHeight + "px").css("left", (imageWidth + (imgPreloader.width + margin * 2) + margin) + "px").css("text-align", "left");
				
				function fixWidthHeight(obj, w, h) {
					if ($.browser.msie && parseInt(jQuery.browser.version) < 7) {
						return $(obj).css("width", w + "px").css("height", h + "px");
					} else {
						return $(obj).css("width", "100%").css("height", "100%");
					}
				}
				function fixPositionFixed(obj, addClass) {
					if ($.browser.msie && parseInt(jQuery.browser.version) < 7) {
						if (addClass) {
							return $(obj).css("position", "absolute").addClass("positionfixed");
						} else {
							return $(obj).css("position", "absolute").css("top", "0");
						}
					} else {
						return $(obj).css("position", "fixed").css("top", "0");
					}
				}
				
				imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs
				return false;
			};
			
			imgPreloader.src = url;
			
			var adcreative = $(this).closest(".rank").find(".adcreative");
			if ($(adcreative)) {
				$("#screener .sidead").html($(adcreative).html());
			}
        }
	});
	$(".rank_vote_button").click(function() { $(this).parent().children('.drop').html(DEFAULT_RANKING_FIELD); });
});


/** Rank AJAX **/
(function($) {
	// constructor
	function Rank(root, conf) {	
		// Private fields ------------------------------------------------------------------
		var RANK_ACTIVATED = "rank_activated";
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_userHasVoted,
			_resultContainer = _root.find('.rank-result-container'),
			_answerElem = _root.find('.rank-answers'),
			_opts = {
				debug: false
			}
			;
			$.extend(_opts, conf);
		
		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					console.log(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
		
		// generic binding function
		
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
			$(_self).bind(name, fn);
		};
		
		function showRankAnswers()
		{
			_resultContainer.hide();
			_answerElem.show();
		};
		
		function showRankResults(submitAnswer){
			backendsumbit(new Array());
			
			return false;
		};
		
		function enableButton(){
			$(".rankVoteButton", _root).removeClass("buttonInactive");
			$(".rankVoteButton", _root).click(function(){
					var must_filled_bit = (1<<0 | 1<<1 | 1<<2);
					var check_filled_bit = 0x0;
					var response_data = new Array();
					var data_string = new Array();
					$(this).closest(".rank-answers").each(
							function (i) { 
									$(this).find(".drop").each( function (i) {
											response_data[i] = (isNaN($(this).children(".label").attr("id"))?0:$(this).children(".label").attr("id"));
											if (response_data[i] > 0) {
												check_filled_bit |= 1<<i;
											}
									});
							});
							
					if ((check_filled_bit & must_filled_bit) == must_filled_bit) {
						data_string.push("response_id=" + response_data.join(","));
						backendsumbit(data_string);
					} else {
						// update poll-results
						_resultContainer.html("Please fill in the Top 3");
						_resultContainer.fadeIn();
					}
					
					return false;
			});
			
			$(".rankClearButton", _root).click(function() { 
					$(this).closest(".rank-answers").each(
							function (i) { 
									$(this).find(".drop").each( function (i) {
											$(this).html(DEFAULT_RANKING_FIELD);
									});
							});
					return false;
			});
		};
		
		function backendsumbit(data_string) {
            $.ajax({
				url: "/scrum/rank_vote.php",
				type: "POST",
				cache: false,
				data: "rank_id=" + _opts.rank_id + "&" + data_string.join("&") + "&rand=" + Math.floor(Math.random()*10000000),
                success: function(html) {
					// update poll-results
					_resultContainer.html(html);
					_resultContainer.fadeIn();
					_userHasVoted = getVoteStatus();
					debug("aft _userHasVoted: " + _userHasVoted);
					if (_userHasVoted == false) showAnswersLink();
                }
            });
		}
		
		function getVoteStatus(){
			var ranks = $.cookie('ranks');
			if (ranks) {
				$(ranks.split('|')).each(function(i) {
					if ($(this) == _opts.rank_id) {
						return true;
					}
				});
			}
			return false;
		};
		
		function init()
		{
			if (!$(_root).hasClass(RANK_ACTIVATED) && ('rank_' + _opts.rank_id) == $(_root).attr("id")) {
				$(_root).addClass(RANK_ACTIVATED);
				// see if user has already voted
				_userHasVoted = getVoteStatus();
				
				debug("_userHasVoted: " + _userHasVoted);
				
				if (_userHasVoted == true) {
					showRankResults();
				} else {
					enableButton();
					showRankAnswers();
				}
			}
		};
		
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.rank = function(conf)
	{
		var opts = { };
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new Rank($(this), opts);
		});
		
		return this;
	};
})(jQuery);
