YUI.add('fantasy-landing-my-teams', function (Y) {
	var User = null,
	$L = Y.Lang;

	var STATE_CLASSES	= {
		'LOGGED_OUT': 'signed-out',
		'LOGGED_IN':  'signed-in-teams',
		'NO_TEAMS':   'signed-in-no-teams',
		'CLOSED':     'signed-in-closed'
	}
	var STATE_NODES		= {
		'LOGGED_OUT': '.nv-fantasy-signed-out',
		'LOGGED_IN':  '.nv-fantasy-signed-in-teams',
		'NO_TEAMS':   '.nv-fantasy-signed-in-no-teams',
		'CLOSED':     '.nv-fantasy-signed-in-closed'
	}
	var STATES = {
		'-1':'logged-out',
		'0' :'logged-in-no-teams',
		'1' :'logged-in-with-teams',
		'2' :'logged-in-with-games',
		'3' :'closed'
	};
	function getNested(field, value, meta) {
	    var fields, obj, i, l, temp;
	    if (! (meta && $L.isObject(value))) {
	        return value;
	    }
	    fields = meta.split('.');
	    obj = value;
	    for (i = 0, l = fields.length; i < l; i = i + 1) {
	        temp = fields[i];
	        if ($L.isUndefined(obj[temp])) {
	            return '';
	        }
	        obj = obj[temp];
	    }
	    return obj;
	}
	var getDraftTime	= function(milTime){
		//console.info('nfl.fantasy.getDraftTime	',milTime);
		var _t	= milTime.split(':');
		// draft time is PST, convert to EST
		//console.info('nfl.fantasy.getDraftTime parseInt('+_t[0]+')	',parseInt(_t[0],10));
		_t[0]	= ((parseInt(_t[0],10)+3) < 24)? (parseInt(_t[0],10) + 3) : ((parseInt(_t[0],10) + 3) - 24);
		//console.info('nfl.fantasy.getDraftTime 1	',_t.join(':'));
		//console.log('getDraftTime',_t);
		var _tRet	= (parseInt(_t[0],10) > 12) ? (parseInt(_t[0],10) - 12) : _t[0];
		//console.info('nfl.fantasy.getDraftTime 2	',_t.join(':'));
		if(parseInt(_t[1],10) > 0){
			_tRet += ':'+((parseInt(_t[1],10) > 9)? _t[1] : '0'+_t[1]);
		}
		//console.info('nfl.fantasy.getDraftTime 3	',_t.join(':'));
		_tRet	+= (parseInt(_t[0],10) > 12) ? ' pm' : ' am';
		//console.info('nfl.fantasy.getDraftTime 4	',_t.join(':'));
		return _tRet;
	}
	var getRankNatural = function(_t){
		var rank		= (_t.place !== null && typeof _t.place !== 'undefined')? _t.place : ((_t.rank !== null)? _t.rank : '0');
		//var rank		= (_t.rank !== null)? _t.rank : ((_t.place !== null)? _t.place : '0');
		var _r	= parseInt(rank);
		var _postfix	= ['th','st','nd','rd','th']; //anything ending in 0 is 20th,30th etc
		if(_r > 9 && _r < 21){ _r = 0; }
		if(_r > 9){ _r = parseInt( (_r+'').substring((_r+'').length -1) );}
		var ret	= ((_r >= _postfix.length)? rank+_postfix[_postfix.length -1] : rank+_postfix[_r] );
		return ret
	}
	var NORMALIZERS	= {
		'league': function(lo,cdate,ctime){
			if(lo.autopick && lo.team === 'undefined'){
				lo.team = {id: lo.id, name: lo.name};
				lo.name = 'Autopick League'
			}
			if(typeof lo.team === 'undefined'){ 
				lo.team = {id: lo.teamId, name: lo.teamName};
			}; // why on earth these feeds are not consistent is beyond me
			if(typeof lo.leagueName !== 'undefined' && typeof lo.name === 'undefined'){
				lo.name	= lo.leagueName;
				lo.id	= lo.leagueId;
			}
			var l	= {
				'leagueId'  : lo.id,
				'leagueName': lo.name,
				'leagueType': ((!lo.autopick)? 'normal' : 'autopick'),
				'leagueTotalTeams': lo.numTeams,
				'teamId'    : lo.team.id,
				'teamName'  : lo.team.name,
				'teamRank'	: getRankNatural(lo.team),
				'teamRecord':lo.team.record,
				'draftDate' : lo.draftDate,
				'draftTime' : lo.draftTime,
				'draftType' : lo.draftType,
				'draftStatus': lo.draftStatus,
				'leagueLink':'<a href="'+nfl.constants.FANTASY_DOMAIN+'/league/'+ lo.id +'">'+ lo.name +'</a>',
				'teamLink':'<a href="'+nfl.constants.FANTASY_DOMAIN+'/league/'+ lo.id +'/team/'+ lo.team.id +'">'+ lo.team.name +'</a>',
				'draftLink':	(nfl.constants.FANTASY_DOMAIN+'/league/'+ lo.id),
				'gameCenterURL': nfl.constants.FANTASY_DOMAIN +'/league/'+lo.id+'/team/'+lo.team.id+'/gamecenter',
				'draftingClass':'not-drafting',
				'place': (lo.team.place !== null && typeof lo.team.place !== 'undefined')? lo.team.place : lo.team.rank,
				'rankClass': (lo.team.place !== null && typeof lo.team.place !== 'undefined')? (((lo.team.place !== null && lo.team.place <= 3) ? 'rank-trophy' : 'rank-standard')) : '',
				'topperformers': {},
				'trophy': ''
			}; 
			console.log('lo',lo);
			console.log('l',l);
			if(l.place !== null && l.place !== ''){ l.trophy = '<img src="'+ nfl.constants.IMAGE_PATH +'/img/fantasy/2011/trophies/standard-'+l.place+'.png"/>'}
			if(lo.autopick){
				l.leagueLink	= lo.name;
				l.teamLink		= lo.team.name;
			}
			if(typeof lo.team.rosters !== 'undefined' && lo.team.place !== null && typeof lo.team.place !== 'undefined'){
				var _tperf	= {'qb':null,'rb':null,'wr':null,'te':null,'lb':null,'db':null,'dl':null,'wr/rb':null,'wr/te':null,'def':null,'k':null};
				
				for(var _pi=0; _pi < lo.team.rosters[0].players.length;_pi++){
					var _p = lo.team.rosters[0].players[_pi];
					if(_tperf[_p.position.toLowerCase()] !== null){ 
						if(typeof _tperf[_p.position.toLowerCase()] !== 'undefined'){
							if(parseInt(_tperf[_p.position.toLowerCase()].fantasyPts.season.pts) < parseInt(_p.fantasyPts.season.pts)){
								_tperf[_p.position.toLowerCase()] =_p; _tperf[_p.position.toLowerCase()].fantasyPts.season.pts = parseInt(_tperf[_p.position.toLowerCase()].fantasyPts.season.pts);
							} 	
						}
					}else{
						_tperf[_p.position.toLowerCase()] = _p; _tperf[_p.position.toLowerCase()].fantasyPts.season.pts = parseInt(_tperf[_p.position.toLowerCase()].fantasyPts.season.pts);
					}
				}
				// now grab just the top two
				//console.log('_tperf',_tperf);
				for(pos in _tperf){
					var _plyr	= _tperf[pos];
					if(_plyr !== null){
						// compare previous values first;
						//console.info('l.topperformers[0] !== null? '+(l.topperformers[0] !== null),l.topperformers[0]);
						if(typeof l.topperformer1 !== 'undefined' && (l.topperformer2 !== _plyr && typeof l.topperformer2 !== 'undefined')){
							if(l.topperformer1.fantasyPts.season.pts < _plyr.fantasyPts.season.pts){ l.topperformer1 = _plyr; /*console.info('		overwriting prev tp1 with new player',_plyr);*/ }
						}
						if(typeof l.topperformer2 !== 'undefined' && (l.topperformer1 !== _plyr && typeof l.topperformer1 !== 'undefined')){
							if(l.topperformer2.fantasyPts.season.pts < _plyr.fantasyPts.season.pts){ l.topperformer2 = _plyr; /*console.info('		overwriting prev tp2 with new player',_plyr);*/ }
						}
						// if values are already null, just add first high scorer
						if(typeof l.topperformer1 === 'undefined' && l.topperformer2 !== _plyr){l.topperformer1 = _plyr; /*console.info('	adding topperformer1',_plyr);*/}
						if(typeof l.topperformer2 === 'undefined' && l.topperformer1 !== _plyr){l.topperformer2 = _plyr; /*console.info('	adding topperformer2',_plyr);*/}
						//if(typeof l.topperformer1 !== 'undefined' && typeof l.topperformer2 !== 'undefined'){ console.log('	breaking out. have two vals',[l.topperformer1,l.topperformer2]); break; }
					}
				}
				//console.info('		l.topperformer1',l.topperformer1);
				///console.info('		l.topperformer2',l.topperformer2);
				if(typeof l.topperformer1 !== 'undefined'){ l.topperformer1.link = (l.topperformer1.pos === 'DEF') ? '/teams/profile?team='+ l.topperformer1.teamAbbr : '/players/'+l.topperformer1.name.toLowerCase().replace(/ /g,'')+'/profile?id='+l.topperformer1.esbid ; }
				if(typeof l.topperformer2 !== 'undefined'){ l.topperformer2.link = (l.topperformer2.pos === 'DEF') ? '/teams/profile?team='+ l.topperformer2.teamAbbr : '/players/'+l.topperformer2.name.toLowerCase().replace(/ /g,'')+'/profile?id='+l.topperformer2.esbid ; }
			}
			if(l.draftDate !== null && typeof l.draftDate !== 'undefined'){
				var ddate	= new Date(l.draftDate.split('-').join('/'));
				if(l.draftTime !== null){
					var _t	= l.draftTime.split(':');
					if((parseInt(_t[0])+3) > 23){
						var _d = l.draftDate.split('-');
						_d[2]	= parseInt(_d[2])+1;
						ddate	= new Date(_d.join('/'));
					}
				}
				l.draftDateTime = (l.draftTime !== null)? (ddate.getAPStyleMonth() + ' ' + ddate.getDate() + '&nbsp;&nbsp;&nbsp;' + getDraftTime(l.draftTime)+' ET') : (ddate.getAPStyleMonth() + ' ' + ddate.getDate()) ;
				
				if(cdate.valueOf() === ddate.valueOf()){
					if(l.draftTime !== null){
						var doArray	=  l.draftTime.split(':'); doArray[0]	= parseInt(doArray[0])+2;
						var doverDT	=  new Date(l.draftDate.split('-').join('/') + ' '+ doArray.join(':'));
						//console.info(cdatetime +' < '+ doverDT.toET()+' ? ',(cdatetime.valueOf() < doverDT.toET().valueOf()));
						if(ctime.valueOf() < doverDT.toET().valueOf()){
							l.draftingClass = 'drafting-today'; //
						}
					}else{
						l.draftingClass = 'drafting-today';
					}
				}
				if(cdate < ddate){
					l.draftingClass = 'drafting-future';
				}
				if(cdate > ddate){
					l.draftingClass = 'drafting-over';
					/* augment */
					
				}
			}
			return l;
		}
	}
	
	function FantasyMyTeamsModule() {
		FantasyMyTeamsModule.superclass.constructor.apply(this, arguments);
	}
	Y.namespace('NFL.Fantasy').MyTeams = Y.extend(FantasyMyTeamsModule, Y.Widget, {
		initializer: function (config) {
			console.info('fantasy my teams initializing..',config);
			this.set('stateNodes',config.stateNodes);
			if(typeof config.pcNodes !== 'undefined'){ this.set('pcNodes',config.pcNodes); }
			
			var usr	= Y.NFL.User.getCurrent();
			if(!usr){
				this.get('srcNode').addClass('module-my-teams-signed-out');
				this.set('userstate',STATES['-1']);
				this.setState();
				return;
			};
			this.set('userstate',STATES['0']); //assume user has no teams for now
			if(typeof config.maxLeagues !== 'undefined'){ this.set('maxLeagues',config.maxLeagues); }
			
			usr.plug(Y.NFL.Fantasy.ServiceUtility);
			this.set('user',usr);
			this.get('handlers')[this.get('handlers').length] = this.get('user').fantasy.on('leaguesinternal:response',Y.bind(this.onLeagueData,this));
			this.get('handlers')[this.get('handlers').length] = this.get('user').fantasy.on('rostersinternal:response',Y.bind(this.onRosterData,this));
			this.get('handlers')[this.get('handlers').length] = this.get('user').fantasy.on('fancookie:response',Y.bind(this.onFanCookieData,this));
			this.get('handlers')[this.get('handlers').length] = this.get('user').fantasy.on('matchups:response',Y.bind(this.onMatchupsData,this));
			this.get('handlers')[this.get('handlers').length] = this.get('pcDS').on('response',Y.bind(this.onPCData,this));
			
			if(typeof config.currentdate !== 'undefined'){ this.set('currentdate',config.currentdate);}
			if(typeof config.currenttime !== 'undefined'){ this.set('currenttime',config.currenttime);}
			
			//this.get('user').fantasy.getService('fancookie'); // this is for in season info
			this.get('user').fantasy.getService('rostersinternal'); // this is the service with end of season info
			this.setState();
		},
		_onSetData: function(value){
			/* take raw roster data and transform it */
			/* split these things up in to two tables per league  */
			//console.log('_onSetData',value);
			if(typeof value === 'undefined'){ return null; }
			return value
		},
		showPCNode: function(node,data){
			var _nodes = this.get('pcNodes');
			for(_k in _nodes){
				if(_k !== node){ 
					console.log('attempting to hide '+_k+' node',_nodes[_k]);
					_nodes[_k].hide(); 
					_nodes[_k].addClass('hidden');
				}else{
					if(typeof data !== 'undefined' && data !== null){
						var _t	= _nodes[_k].get('innerHTML');
						data.teamlink	= '<a href="'+ nfl.constants.PLAYOFF_CHALLENGE_DOMAIN +'/playoffchallenge">'+ data.name +'</a>';
						_nodes[_k].setContent(Y.substitute(_t,data));
					}
					_nodes[_k].removeClass('hidden');
					_nodes[_k].show();
				}
			}
			// force the last one in case the other iters hid it(used the same id/node)
			try{
				_nodes[node].removeClass('hidden');
				_nodes[node].show();
			}catch(e){ console.warn('show node error',e,node); }
		},
		getPCData: function(usr){
			_pcds = this.get('pcDS');
			_pcds.source = (nfl.constants.PLAYOFF_CHALLENGE_DOMAIN+'/playoffchallenge/entry_status/'+usr.get('username')+'?');
			_pcds.set('source',nfl.constants.PLAYOFF_CHALLENGE_DOMAIN+'/playoffchallenge/entry_status/'+usr.get('username')+'?');
			_pcds.sendRequest();
		},
		onPCData: function(r){
			console.info('PLAYOFF CHALLENGE RESPONSE: ',r);
			try{
			if(r.response !== null){
				if(r.response.results !== null){
					if(r.response.results.length > 0){
						var _r = r.response.results[0];
						if(typeof _r !== 'undefined' && _r !== null){
							if(_r !== null && _r.entry !== null && _r.error === null){
								// has pc, has teams
								if(_r.entry.lineup_set !== true && this.get('pcNodes.no-lineup') !== null){
									// no lineup set
									this.showPCNode('no-lineup', _r.entry);
									return
								}
								// has teams and or lineup set, show editorial cp
								console.log('has teams and or lineup set');
								// line up, has teams
								this.showPCNode('logged-in-with-teams', _r.entry);
								return
							}
						}
						// signed in without team, do default
					}
				}
			}
			}catch(e){ console.error('fibbledeejibbits!',e); }
			// default: show 3
			this.showPCNode('logged-in-no-teams');
			// signed in without teams
			return
		},
		onRosterData: function(r){
			console.info('onrosterdata',r);
			var _ldata	= [];
			if(r.data.leagues.length > 0 || r.data.autopicks.length > 0){
				this.set('userstate',STATES['1']); //user has leagues with teams
				Y.Array.each(r.data.leagues, function(l){
					_ldata[_ldata.length]	= l;
					//console.info('onRosterData League Nomalizer', NORMALIZERS['league'](l));
				},this)
				Y.Array.each(r.data.autopicks, function(l){
					l.autopick = true;
					_ldata[_ldata.length]	= l;
				},this)
			};
			this.set('leagues',_ldata);
			this.onRender();
			this.setState();
		},
		onLeagueData: function(r){
			console.info('onleaguedata',r);
			var _ldata	= [];
			if(r.data.leagues.length > 0 || r.data.autopicks.length > 0){
				this.set('userstate',STATES['1']); //user has leagues with teams
				Y.Array.each(r.data.leagues, function(l){
					_ldata[_ldata.length]	= l;
				},this)
				Y.Array.each(r.data.autopicks, function(l){
					l.autopick = true;
					_ldata[_ldata.length]	= l;
				},this)
			};
			this.set('leagues',_ldata);
			this.onRender();
			this.setState();
		},
		onFanCookieData: function(r){
			//console.info('fancookiedata',r);
			var _ldata	= [];
			if(r.data.leagues.length > 0 || r.data.autopicks.length > 0){
				this.set('userstate',STATES['1']); //user has leagues with teams
				Y.Array.each(r.data.leagues, function(l){
					_ldata[_ldata.length]	= l;
				},this)
				Y.Array.each(r.data.autopicks, function(l){
					l.autopick = true;
					_ldata[_ldata.length]	= l;
				},this)
			}
			this.set('leagues',_ldata);
			this.onRender();
			this.setState();
		},
		onMatchupsData: function(r){
			//console.info('onMatchupsData',r);
			this.set('userstate',STATES['2']); //user has active games
			this.set('matchups',r.response);
			this.setState();
			var leagues				= this.get('leagues');
			var matchups_in		= r.response;
			var matchups_out	= {}; 
			Y.Array.each(matchups_in,function(resp){
				var _l	= resp.leagues[0];
				var _m	= _l.matchup;
				matchups_out[_l.id]		= _m;
			},this);
			this.set('matchups',matchups_out);
			this.onRender();
		},
		setState: function(){
			//console.info('setState',this.get('userstate'));
			for(key in STATES){ var s = STATES[key]; this.get('srcNode').removeClass(s); }
			this.get('srcNode').addClass(this.get('userstate'));
			if(this.get('user') !== null){
				this.getPCData(this.get('user'));
			}else{
				this.showPCNode('logged-out'); // set it to just default
			}
		},
		applyUser: function(){
			var cNode	= this.get('stateNodes')[this.get('userstate')];
			var _t	= cNode.get('innerHTML').replace('data-','');
			cNode.setContent(Y.substitute(_t,{user: this.get('user').getAttrs()},getNested));
		},
		onRender: function(){
			//console.info('onRender',this.getAttrs());
			try{
				var cNode	= this.get('stateNodes')[this.get('userstate')];
				var template = this.get('templates')[this.get('userstate')];
				//console.log('user state',this.get('userstate'));
	
				if(cNode.one('.template') !== null && typeof template === 'undefined'){
					var templates	= this.get('templates');
					templates[this.get('userstate')] = cNode.one('.template').get('innerHTML').replace(/data-/g,'');
					this.set('templates',templates);
					template = this.get('templates')[this.get('userstate')];
				}
				
				if(this.get('userstate') == 'logged-in-with-teams'){
					// render just league data, no games
					var output	= '';
					var data		= this.get('leagues');
					//console.log('leagues',data);
					Y.Array.each(data,function(l,ind){
						//console.log('getting templated content for',l);
						if(ind < this.get('maxLeagues')){
							output += Y.substitute(template,NORMALIZERS['league'](l,this.get('currentdate'),this.get('currenttime')),getNested);
						}
					},this);
					cNode.one('.target').setContent(output);
				}
				if(this.get('userstate') == 'logged-in-with-games'){
					var output	= '';
					var data		= this.get('leagues');
					//console.log('leagues',data);
					Y.Array.each(data,function(l){
						var l	= NORMALIZERS['league'](l,this.get('currentdate'),this.get('currenttime'));
						if(this.get('matchups') !== null){
							if(typeof this.get('matchups')[l.leagueId] !== 'undefined'){ 
								l.matchups = this.get('matchups')[l.leagueId]; 
							}
						}
						console.log('getting templated content for',l);
						output += Y.substitute(template,l,getNested);
					},this);
					cNode.one('.target').setContent(output);
				}
				this.applyUser();
			
			}catch(e){ console.error('whut',e); }
		},
		destructor: function(){
			
			Y.Array.each(this.get('handlers'),function(h){
				h.detach();
			},this);
		}
	}, {
		NAME: 'MyTeams',
		ATTRS: {
			data: {value: null, setter: '_onSetData'},
			user: {value: null},
			stateNodes: {value: null},
			pcNodes: {value: null},
			pcDS: {value: (new Y.DataSource.Get({
				source: 'http://stage.challengegames.nfl.com/playoffchallenge/entry_status/'
			}))},
			matchups: {value: null},
			inactives: {value: null},
			leagues: {value: null},
			handlers: {value: []},
			userstate: {value:null},
			templates: {value: []},
			currentdate: {value: (new Date())},
			currenttime: {value: (new Date())},
			maxLeagues: {value: 3}
		}
	});
}, "3.1.1", { requires: ['base','widget','nfl-lang','array-extras','substitute','nfl-user-fantasy', 'nfl-user']});

YUI.add('fantasy-accordion', function (Y) {
	
	function FantasyAccordion() {
		FantasyAccordion.superclass.constructor.apply(this, arguments);
	}
	Y.extend(FantasyAccordion, Y.Widget, {
		initializer: function (config) {
			this._closedClass = this.getClassName('closed');
			this._openClass = this.getClassName('open');
			if(typeof config.subheadHeight !== 'undefined'){ this.set('subheadHeight',config.subheadHeight); }
		},
		renderUI: function () {
			
		},
		_closeGroup: function (g) {
			var anim = g._anim;
			anim.set('reverse', true);
			if (! anim.get('running')) {
				anim.run();
			}
		},
		_onLabelClick: function (event) {
			console.log('_onLabelClick', event);

			var group = event.currentTarget.ancestor(this.get('groupSelector')),
				anim = group._anim;
			
			// do nothing if we're already open
			if (group.hasClass(this._openClass)) {
				return;
			}
			console.log(group.siblings('.' + this._openClass)._nodes);
			group.siblings('.' + this._openClass).each(this._closeGroup);
			group.replaceClass(this._closedClass, this._openClass);
			anim.set('reverse', false);
			if (! anim.get('running')) {
				anim.run();
			}
		},
		bindUI: function () {
			this._labelClickHandler = Y.delegate('click', this._onLabelClick, this.get('contentBox'), this.get('labelSelector'), this);
		},
		_onAnimEnd: function (event) {
			var anim = event.target,
				node = anim.get('node');
			
			if (anim.get('reverse')) {
				node.replaceClass(this._openClass, this._closedClass);
				node.setStyle('height', anim.get('from.height') + 'px');
			}
		},
		_initializeGroups: function (group, index, nodeList) {
			var subhead_height	= this.get('subheadHeight');
			var contentHeight = group.one(this.get('contentSelector')).get('offsetHeight'),
				openHeight    = group.get('offsetHeight') + subhead_height,
				closedHeight  = openHeight - subhead_height - contentHeight;
			
			if (index > 0) {
				group.addClass(this._closedClass);
				group.setStyle('height', closedHeight + 'px');
			}
			else {
				group.addClass(this._openClass);
			}
			group._anim = new Y.Anim({
				node: group,
				to: {
					height: openHeight
				},
				from: {
					height: closedHeight
				},
				duration: 0.5,
				easing: Y.Easing.easeOut
			});
			group._animEndHandler = group._anim.on('end', this._onAnimEnd, this);
		},
		syncUI: function () {
			this.get('srcNode').all(this.get('groupSelector')).each(this._initializeGroups, this);
		},
		_destroyGroupAnims: function (group) {
			group._animEndHandler.detach();
			group._anim.destroy;
			delete group._animEndHandler;
			delete group._anim;
		},
		destructor: function () {
			_labelClickHandler.detach();
			this.get('srcNode').all(this.get('groupSelector')).each(this._destroyGroupAnims);
		}
	}, {
		NAME: 'fantasy-accordion',
		ATTRS: {
			labelSelector: { value: '.label' },
			groupSelector: { value: '.group' },
			contentSelector: { value: '.content'},
			subheadHeight: {value: 0}
		}
	});
	
	Y.namespace('NFL.Fantasy').FantasyAccordion = FantasyAccordion;
}, "3.1.1", { requires: ['anim', 'widget']});

YUI.add('fantasy-player-rankings-tabbed', function (Y) {
	function PlayerRankingsTabbed() {
		PlayerRankingsTabbed.superclass.constructor.apply(this, arguments);
	}
	Y.namespace('NFL.Fantasy').PlayerRankingsTabbed = Y.extend(PlayerRankingsTabbed, Y.Widget, {
		initializer: function (config) {
			if(typeof config.datacleaner === 'function'){ 
				this.dataScrubber = Y.bind(config.datacleaner,this);
			}
			this.set('data',config.data);
			this.set('season',config.season);
			this.set('seasonType',config.seasonType);
			this.set('week',config.week);
			this.set('rows',config.rows);
			
			// create tabset
			var tabview = new Y.TabView({
				srcNode: this.get('srcNode')
			});
			tabview.plug(Y.TabViewDeepLinker);
			this.set('tabset',tabview);
			this.get('tabset').on('selectionChange',this.onTabChange,this);
			this.get('tabset').render();
		},
		dataScrubber: function(value){
			return value
		},
		changeTitle: function(position){
			var _title = 'Player Rankings: '+ this.get('positionNames')[position] + ' - ';
			if(this.get('seasonType') === 'PRE'){ _title += 'PRESEASON'; }
			if(this.get('seasonType') === 'REG'){ 
				_title += 'WEEK '+this.get('week'); 
			}
			if(this.get('seasonType') === 'POST'){ _title += 'POSTSEASON'; }
			document.title	= _title;
		},
		onTabChange: function(e){
			
			console.log('onTabChange',e.newVal);
			if(e.newVal !== e.prevVal){
				var srcNode	= e.newVal.get('srcNode');
				var _href	= srcNode.get('href');
				var _target	= _href.substring(_href.indexOf('#')+1);
				var _type	= _target.substring(_target.indexOf('-')+1);
				
				this.changeTitle(_type);
				if(typeof this.get('writeCache')[_type] === 'undefined'){
					// write the results out
					this.writeOutTabContent(_type,_target);
				}
			}
		},
		writeOutTabContent: function(position,target){
			console.info('writeOutTabContent '+position+' to '+target);
			console.log('	data',this.get('data'));
			var _target		= Y.one('#'+target).one('table tbody');
			var _content	= '';
			var _d			= this.get('data')[position].players;
			var _t			= this.get('rows')[position].template;
			var _m			= this.get('rows')[position].limit;
			for(var _r=0, _l=((_d.length > _m) ? _d.length : _m); _r < _l; _r++){
				var _p = _d[_r];
				_content	+= Y.substitute(_t,_p);
			}
			_target.setContent(_content);
		},
		renderUI: function(){},
		destructor: function(){

		}
	},{
		NAME: 'PlayerRankingsTabbed',
		ATTRS: {
			'data': {value: null, setter: 'dataScrubber'},
			'datacleaner': {value: null},
			'positionNames': {
				value: {
					'top':'Top 200',
					'qb':'Quarterbacks',
					'rb':'Running backs',
					'rb-ppr':'Running backs',
					'wr':'Wide receivers',
					'wr-ppr':'Wide receivers',
					'te':'Tight ends',
					'te-ppr':'Tight ends',
					'k':'Kickers',
					'dst':'Defenses',
					'def':'Defenses',
					'dl':'Defensive Linemen',
					'lb':'Line Backers',
					'db':'Defensive Back'
				}
			},
			'writeCache':{ value: {}},
			'season':{value: null},
			'seasonType': {value: null},
			'templates': {value:{}},
			'rows': {value: {}},
			'week':{value:null},
			'tabset': {value: null}
		}
	});
}, "3.1.1", { requires: ['node', 'widget', 'base','substitute','tabview','tabview-deeplinker']});
