/*****************************
		MY NFL MODULE
******************************/
YUI.add('nfl-my-nfl', function (Y) {	
	var USER = Y.NFL.User,
		ABUSE_THRESHOLD = 3;
	
	// create widget class so scoutingWidget tag can use it
	function MyNFL(config) {
		MyNFL.superclass.constructor.apply(this, arguments);
	}

	Y.namespace('NFL').MyNFL = Y.Base.create('nfl-my-nfl', Y.Widget, [Y.WidgetFold], {

		initializer: function (config) {
			var user = USER.getCurrent();
			this.set('fantasyData',null).set('json', {});
			if (user) {
				this.set('user',user).set('json.user', user.getAttrs()).set('userName',true);			
			}			
			this.set('modulePlaceHolder',Y.Node.create('<ol class="my-nfl"></ol>'));
		},
		destructor: function () {},
		renderUI: function () {
			Y.on('my-nfl:signInComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:fantasyComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:newsComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:nextGameComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:shopComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:facebookFriendActivityComplete',Y.bind(this._accordionReadyCheck,this));
			Y.on('my-nfl:facebookRecommendComplete',Y.bind(this._accordionReadyCheck,this));

			if(this.get('userName')){
				this._signedIn();
			}else{
				this._notSignedIn();
			}
		},
		bindUI: function(){

		},
		syncUI: function(){},
		_notSignedIn : function(){
			var moduleOrder = this.get('moduleSelect');
			
			var signInState = Y.Node.create(this.get('signInTemplate')),
				fantasySignInState = Y.Node.create(this.get('fantasySignInTemplate')),
				facebookRecommend = Y.Node.create(this.get('facebookRecommendSignInTemplate')),
				url = nfl.constants.ID_MANAGER+'/fans/login?returnTo='+encodeURIComponent(window.location.href),
				paramsUrl = Y.Lang.addParamsToURL(url,this.get('omnitureModule')),
				SignInLink = Y.Node.create('<a href="'+paramsUrl+'" name="&amp;lid=Signin&amp;lpos=MyNFL_Signin" class="sign-in-team-link">SIGN IN</a>'),
				modulePlaceHolder = this.get('modulePlaceHolder'),
				modulesEnabled = this.get('moduleEnabled');
			for(var i=0;i<moduleOrder.length;i++){
				if((moduleOrder[i] === 'shop') || (moduleOrder[i] === 'fantasy') || (moduleOrder[i] === 'sign-in') || (moduleOrder[i] === 'facebook-recommend')){
					for(var j=0;j<modulesEnabled.length;j++){
						if(moduleOrder[i] === modulesEnabled[j]){
							modulePlaceHolder.append(Y.Node.create('<li class="'+moduleOrder[i]+'-ph"></li>'));
							break;
						}
					}
				}
			}
			
			Y.one('#my-nfl .header').prepend(SignInLink);
			
			if(modulePlaceHolder.one('.sign-in-ph') !== null){
				modulePlaceHolder.one('.sign-in-ph').replace(signInState);
			}
			if(modulePlaceHolder.one('.fantasy-ph') !== null){
				modulePlaceHolder.one('.fantasy-ph').replace(fantasySignInState);
			}
			if(modulePlaceHolder.one('.facebook-recommend-ph') !== null){
				modulePlaceHolder.one('.facebook-recommend-ph').replace(facebookRecommend);
			}
			if(modulePlaceHolder.one('.shop-ph') !== null){
				this._getShopInfo('NFL');
			}
			
			Y.one('#my-nfl').append(modulePlaceHolder);
		},
		_signedIn: function(){
			var userInfo = this.get('json');				
			
			var modules = this.get('moduleSelect');
			var modulesEnabled = this.get('moduleEnabled');
			var modulePlaceholder = this.get('modulePlaceHolder');
			//modulePlaceholder.append(Y.Node.create('<li class="sign-in-ph"></li>'));	
			Y.log(modulesEnabled);
			for(var i=0;i<modules.length;i++){
				for(var j=0;j<modulesEnabled.length;j++){
					if(modules[i] === modulesEnabled[j]){
						modulePlaceholder.append(Y.Node.create('<li class="'+modules[i]+'-ph"></li>'));
						break;
					}
				}
				
			}
			
			if((userInfo.user.team !== '') && (userInfo.user.team !== ' ')){
				this._signedInTeam();			
			}else{
				this._signedInNoTeam();
			}
		},
		_setUserAvatar : function(e){
			var modulePlaceholder = this.get('modulePlaceHolder');
			var NO_USER_IMAGE = /\/images\/no\-user\-image\.gif$/,
				_user = e[0].User,
		    	avatar = (NO_USER_IMAGE.test(_user.AvatarPhotoUrl) || _user.AbuseCounts.CurrentUserHasReportedAbuse || _user.IsBlocked || _user.AbuseCounts.AbuseReportCount > ABUSE_THRESHOLD) ? '' : ('<img src="' + _user.AvatarPhotoUrl + '" alt="" />');

			if(avatar !== ''){
				modulePlaceholder.one('.my-nfl-module.signed-in .user-image').append(avatar);
			}
		},
		_signedInNoTeam : function(){
			var url = '/fans/edit-profile',
				paramsUrl = Y.Lang.addParamsToURL(url,this.get('omnitureModule'));
			var chooseTeamLink = Y.Node.create('<a href="'+paramsUrl+'" class="choose-team-link" name="&amp;lid=Choose%20Your%20Team&amp;lpos=MYNFL_chooseTeamHeader">CHOOSE YOUR TEAM</a>');
			Y.one('#my-nfl .header').prepend(chooseTeamLink);
			this._createTeamModules('NFL');
		},
		_signedInTeam : function(){
			var url = '/teams/profile?team='+this.get('json').user.team,
				paramsUrl = Y.Lang.addParamsToURL(url,this.get('omnitureModule'));
			var teamHeaderLogo = Y.Node.create('<a href="'+paramsUrl+'" name="&amp;lid=Favorite%20Team%20Logo&amp;lpos=MYNFL_favTeamImage"><img class="team-logo" src="'+nfl.constants.IMAGE_PATH+'/img/logos/my-nfl-logos/'+this.get('json').user.team+'-40x40.png" atl=""/></a>');
			Y.one('#my-nfl .header').prepend(teamHeaderLogo);
			this._getTeamData(this.get('json').user.team);
		},
		_getTeamData :function(team){
			var request = Y.io('/ajax/community/toptenvideos?teamAbbr='+team, {
					method:"GET",on: {success:Y.bind(this._teamDataSuccess,this),failure:this._signedInNoTeam}
				}
			);	
		},
		_teamDataSuccess : function(id,o){
			var teamInfo, hostWidget = this;
			try{
				teamInfo = Y.JSON.parse(o.responseText);
				hostWidget.set('teamInfo',teamInfo);
				hostWidget._createTeamModules();
			}catch(e){
				Y.log(e);
			}				
		},
		_createTeamModules : function(){			
			var modulesEnabled = this.get('moduleEnabled');
			var team = (this.get('teamInfo') === undefined) ? 'NFL' : this.get('teamInfo').team;
			for(i=0;i<modulesEnabled.length;i++){
				switch(modulesEnabled[i]){
					case 'sign-in':
						this._createSignInModule();
						break;
					case 'fantasy':
						this._getFantasyData();
						break;
					case 'news':
						this._getLatestNews();
						break;
					case 'next-game':
						this._createNextGameModule();
						break;
					case 'facebook-activity':
						this._createFacebookFriendActivityModule('signedIn');
						break;
					case 'facebook-recommend':
						this._createFacebookRecommendModule();
						break;
					case 'shop':
						this._getShopInfo(team);
						break;
				}
				
			}
		},
		_createSignInModule :function(){
			Y.log(this.get('teamInfo') === undefined);
			var modulePlaceholder = this.get('modulePlaceHolder'),
				userInfo = this.get('json'),
				userReq = new PluckSDK.UserRequest(),
				signedInState = Y.Node.create(this.get('signedInTemplate'));			
			modulePlaceholder.one('.sign-in-ph').replace(signedInState);
			
			if(this.get('teamInfo') === undefined){
				var noTeam = this.get('noTeam');
				modulePlaceholder.one('.sign-in-text p:first-child').setStyle('marginTop','0px');
				modulePlaceholder.one('.sign-in-text').append(noTeam);
				
			}
			
			signedInState.one('.user-name').set('text',userInfo.user.username);
			signedInState.one('.user-profile').set('href',Y.Lang.addParamsToURL(userInfo.user.profilePageURL,this.get('omnitureModule')));
			signedInState.one('.user-image').set('href',Y.Lang.addParamsToURL(userInfo.user.profilePageURL,this.get('omnitureModule')));
			//Y.one('#my-nfl').append(modulePlaceholder);
			//PLUCK STUFF FOR AVATAR
			userReq.UserKey = new PluckSDK.UserKey({Key:userInfo.user.username});
			PluckSDK.SendRequests([userReq],Y.bind(this._setUserAvatar,this));
			Y.fire('my-nfl:signInComplete');
		},
		_getFantasyData :function(){
			var user = this.get('user');			
			user.plug(Y.NFL.Fantasy.ServiceUtility);
			user.fantasy.on('fancookie:response',this._setFantasyData,this);
			user.fantasy.on('leaguesinternal:response',this._setFantasyData,this);
			user.fantasy.on('error',function(){
				this.set('fantasyData',null);
				this._createFantasyModule();		
			},this);
			user.fantasy.on('leaguesinternal:error',function(){})
			if(user.get('fantasyDataSource')){
				user.fantasy.getService('fancookie');
			}else{
				user.fantasy.getService('leaguesinternal');
			}
		},
		_setFantasyData : function(e){
			if(e.data === 'null'){
				return;
			}
			var leagues = e.data.leagues;
			if(leagues.length > 0){
				this.set('fantasyData',e.data);
			}else{
				this.set('fantasyData',null);
			}
			this._createFantasyModule();
		},
		_createFantasyModule : function(){
			
			var fantasyData = this.get('fantasyData');
			var modulePlaceHolder = this.get('modulePlaceHolder');
			if(fantasyData !== null){
				
				var leagues = fantasyData.leagues,
					fantasyModule = Y.Node.create(this.get('fantasySignedInTemplate'));	

				modulePlaceHolder.one('.fantasy-ph').replace(fantasyModule);
				
				for(var i in leagues){
					if(parseInt(i,10) < 3){
						var lastClass = ((parseInt(i)+1) == leagues.length) ? ' class="last" ' : '' ;
						var url = 'http://qa.fantasy.nfl.com/league/'+leagues[i].id+'/team/'+leagues[i].team.id;
						var paramsUrl = Y.Lang.addParamsToURL(url,this.get('omnitureModule'))
						var leagueInfo = '<dt><a href="'+paramsUrl+'" name="&amp;lid=Pick%20A%20Team&amp;lpos=MYNFL_fantasyLeague'+(parseInt(i,10)+1)+'">'+leagues[i].team.name+'</a></dt><dd'+lastClass+'>In: <a href="http://qa.fantasy.nfl.com/league/'+leagues[i].id+'">'+leagues[i].name+'</a></dd>';
						fantasyModule.one('.fantasy-leagues').append(leagueInfo);
					}else{
						break;
					}
				}
			}else{
				var fantasyModule = Y.Node.create(this.get('fantasySignInTemplate'));
				modulePlaceHolder.one('.fantasy-ph').replace(fantasyModule);
			}
			Y.fire('my-nfl:fantasyComplete');
		},
		_getLatestNews : function(){
			if(this.get('teamInfo') === undefined){
				var modulePlaceHolder = this.get('modulePlaceHolder');
				modulePlaceHolder.one('.news-ph').remove();
				Y.fire('my-nfl:newsComplete');
				//this._createNewsModule(1, null);
			}else{
				var team = this.get('teamInfo').team,
					request = Y.io('/widget/team-news?team='+team+'&maxArticles=5', {
						method:"GET",on: {success:Y.bind(this._createNewsModule,this),failure:this._createNextGameModule}
					}
				);
			}
		},
		_createNewsModule : function(id,o){
			var modulePlaceHolder = this.get('modulePlaceHolder'),
				newsModule = Y.Node.create(this.get('newsTemplate'));
			modulePlaceHolder.one('.news-ph').replace(newsModule);
			if(o === null){
				var noTeam = this.get('noTeam');
				newsModule.all('.news-team').set('text','Team ');
				newsModule.one('.content').empty().prepend(noTeam);
			}else{
				var newsList = Y.Node.create(o.responseText),
					team = this.get('teamInfo').team,
					teamInfo = this.get('teamsInfo');
					newsList.one('li').addClass('first');
					newsList.all('a').each(function(a,b){						
						a.set('href',Y.Lang.addParamsToURL(a.get('href'),this.get('omnitureModule'))).set('name','&lid=&lpos=MYNFL_news'+(parseInt(b,10)+1));
					},this)
					newsModule.one('.content').prepend(newsList);
					newsModule.all('.news-team').set('text',teamInfo[team].nickname+' ');
					var url = 'http://search.nfl.com/search?query='+teamInfo[team].city+'%20'+teamInfo[team].nickname;
					var paramsUrl = Y.Lang.addParamsToURL(url,this.get('omnitureModule'));
					newsModule.one('.more').set('href',paramsUrl);
			}	
			
			Y.fire('my-nfl:newsComplete');
		},
		_createNextGameModule : function(){			
			var modulePlaceHolder = this.get('modulePlaceHolder'),
			nextGameModule = Y.Node.create(this.get('nextGameTemplate'));
			if(this.get('teamInfo') === undefined){
				modulePlaceHolder.one('.next-game-ph').remove();
				Y.fire('my-nfl:nextGameComplete');
			}else{
				modulePlaceHolder.one('.next-game-ph').replace(nextGameModule);
				
				var teamInfo = this.get('teamInfo'),
					teamsInfo = this.get('teamsInfo'),
					team = teamInfo.team,
					gameSchedule = teamInfo.gameSchedule,
					gameTime = Y.Date.toET(new Date(gameSchedule.gameDateTime)),
					weekday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
					months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'],
					gameMonth = months[gameTime.getMonth()],
					gameMonthDate = gameTime.getDate(),
					gameYear = gameTime.getFullYear(),
					gameDate = weekday[gameTime.getDay()],
					gameHours = gameTime.getHours() >12 ? gameTime.getHours() - 12 : gameTime.getHours(),
					gameMinutes = gameTime.getMinutes(),
					gameMinutes = (parseInt(gameMinutes,10) < 10) ?'0'+gameMinutes : gameMinutes,
					gameAMPM = gameTime.getHours() > 12 ? 'P.M.':'A.M.',
					gameDateTime =  gameMonth +'. '+gameMonthDate+', '+gameYear+' AT '+ gameHours + ':'+gameMinutes+' '+gameAMPM+' ET',
					gameCenterLink = Y.Lang.addParamsToURL('/gamecenter/'+gameSchedule.gameId+'/'+gameSchedule.season+'/'+gameSchedule.seasonType+gameSchedule.week,this.get('omnitureModule')),
					gameTv = [];
				if(gameSchedule.network !== ''){gameTv.push('TV : '+gameSchedule.network);}
				if(gameSchedule.satelliteTv !== ''){gameTv.push('DirecTV : '+gameSchedule.satelliteTv);}
				//if(gameSchedule.hdSatelliteTv !== ''){gameTv.push(gameSchedule.hdSatelliteTv);};
				
				nextGameModule.one('.accordion-heading a').set('text',(teamsInfo[team].nickname+' Matchup'));
				nextGameModule.one('.away-team').set('text',gameSchedule.visitorNickname);
				nextGameModule.one('.home-team').set('text',gameSchedule.homeNickName);
				nextGameModule.one('.game-time').set('text',gameDateTime);
				nextGameModule.one('.away-helmet').set('src',nfl.constants.IMAGE_PATH+'/img/logos/my-nfl-helmets/away/'+gameSchedule.visitorTeamAbbr+'-away-130x115.png')
				nextGameModule.one('.home-helmet').set('src',nfl.constants.IMAGE_PATH+'/img/logos/my-nfl-helmets/home/'+gameSchedule.homeTeamAbbr+'-home-130x115.png')
				nextGameModule.one('.team-lineup').set('href',gameCenterLink);
				nextGameModule.all('.team-helmet-link').set('href',gameCenterLink);
				nextGameModule.one('.game-tv-channels').set('text',gameTv.join(' | '));
				nextGameModule.one('.game-center').set('href',gameCenterLink);
				Y.fire('my-nfl:nextGameComplete');
			}
			
		},
		_getShopInfo : function(team){		
			if(team === 'NFL'){
				var request = Y.io('/widget/shop/products?searchType=latest&searchTerm=&quantity=2&viewName=widget/global/shop', {
						method:"GET", on:{success:Y.bind(this._createShopModule,this,team)}
					}
				);
			}else{
				var request = Y.io('/widget/shop/products?searchType=team&searchTerm='+team+'&quantity=2&viewName=widget/global/shop', {
						method:"GET", on:{success:Y.bind(this._createShopModule,this,team)}
					}
				);
			}
		},
		_createShopModule : function(team,id,o){
			var modulePlaceHolder = this.get('modulePlaceHolder');
			var teamsInfo = this.get('teamsInfo');
			var	teamName = (this.get('teamInfo') === undefined) ? 'NFL SHOP ': teamsInfo[team].nickname + ' ';
			var shopModule = Y.Node.create(this.get('shopTemplate')),
				shopContents = Y.Node.create(o.responseText);
			
			shopContents.all('.thumbnail a').each(function(a,i){
				var paramsUrl = Y.Lang.addParamsToURL(a.get('href'),this.get('omnitureModule'));
				a.set('href',paramsUrl).set('name','&lid=Product%20Image&lpos=MYNFL_productImage'+(parseInt(i,10)+1));
			},this);
			
			shopContents.all('.content a').each(function(a,i){
				var paramsUrl = Y.Lang.addParamsToURL(a.get('href'),this.get('omnitureModule'));
				a.set('href',paramsUrl).set('name','&lid=Product%20Text&lpos=MYNFL_productText'+(parseInt(i,10)+1));
			},this);
			
			modulePlaceHolder.one('.shop-ph').replace(shopModule);
			shopModule.one('.shop-wrapper').append(shopContents);
			shopModule.all('.shop-team').set('text',teamName);
			
			Y.fire('my-nfl:shopComplete');
		},
		_createFacebookFriendActivityModule : function(signinState){
			var modulePlaceHolder = this.get('modulePlaceHolder');
			var facebookActivityModule = (signinState === 'signedIn') ? Y.Node.create(this.get('facebookFriendActivitySignedInTemplate'))	: Y.Node.create(this.get('facebookFriendActivitySignInTemplate'));
			modulePlaceHolder.one('.facebook-activity-ph').replace(facebookActivityModule);
			Y.fire('my-nfl:facebookFriendActivityComplete');
		},
		_createFacebookRecommendModule : function(){
			var modulePlaceHolder = this.get('modulePlaceHolder');
			var facebookRecommendModule = Y.Node.create(this.get('facebookRecommendTemplate'));
			modulePlaceHolder.one('.facebook-recommend-ph').replace(facebookRecommendModule);			
			Y.fire('my-nfl:facebookRecommendComplete');
		},
		_accordionReadyCheck : function(e){
			var moduleLength = this.get('moduleEnabled').length;
			var accordionCount = parseInt(this.get('accordionCheck'))+1;
			
			if(accordionCount === moduleLength){
				Y.one('#my-nfl').append(this.get('modulePlaceHolder'));
				this._createAccordion();
			}else{
				this.set('accordionCheck',accordionCount);
			}
		},
		_createAccordion : function(){	
			/*ONLY ONE OPEN ACCORDION FUNCTIONS
			Y.all('.accordion-heading').each(function(node,i){
				if(i !== 0){
					node.siblings('.content').setAttribute('data-height',node.siblings('.content').getStyle('height')).setStyle('height',0).setStyle('paddingTop',0).setStyle('paddingBottom',0);
				}else{
					node.siblings('.content').setAttribute('data-height',node.siblings('.content').getStyle('height'));
					node.ancestor('.accordion').addClass('selected');
				}
			});
			//LISTEN FOR CLICKS
			Y.all('.accordion-heading').on('click',function(e){
				if(e.currentTarget.ancestor('.accordion').hasClass('selected') === false){
					if(Y.one('.accordion.selected')){
						Y.one('.accordion.selected .content').transition({easing:'ease-in',duration:.4,height:'0px',paddingTop:'0px',paddingBottom:'0px'});
						Y.one('.accordion.selected').removeClass('selected');
					}
					Y.one(e.currentTarget).ancestor('.accordion').addClass('selected');
					Y.one('.accordion.selected .content').transition({easing:'ease-in',duration:.4,height:Y.one(e.currentTarget).siblings('.content').getAttribute('data-height'),paddingTop:'10px',paddingBottom:"10px"});
				}else{
					Y.one('.accordion.selected .content').transition({easing:'ease-in',duration:.4,height:'0px',paddingTop:'0px',paddingBottom:'0px'});
					Y.one('.accordion.selected').removeClass('selected');
				}
				e.preventDefault();
			});
			*/
			/*ALL CAN OPEN AT ONCE ACCORDION*/
			var openedAccordions = this.get('moduleEnabled');
			Y.all('.accordion-heading').each(function(node,i){
				var selected = false;
				
				for(i=0;i<openedAccordions.length;i++){	
					switch(openedAccordions[i]){
						 case 'facebook-activity':
							 openedAccordions[i] = 'facebook-friend-activity';
							 break;
						 case 'facebook-recommend':
							 openedAccordions[i] = 'facebook-recommendations';
							 break;
					}

					if(node.ancestor('.accordion').hasClass(openedAccordions[i])){
						selected = true;
						break;
					}
				}
				if(selected === true){
					node.siblings('.content').setAttribute('data-height',node.siblings('.content').getStyle('height'));				
					node.ancestor('.accordion').addClass('selected');
				}else{
					node.siblings('.content').setAttribute('data-height',node.siblings('.content').getStyle('height')).setStyle('height',0).setStyle('paddingTop',0).setStyle('paddingBottom',0);
				}
			});
			//LISTEN FOR CLICKS
			Y.all('.accordion-heading').on('click',function(e){
				if(e.currentTarget.ancestor('.accordion').hasClass('selected') === false){
					Y.one(e.currentTarget).ancestor('.accordion').addClass('selected');
					Y.one(e.currentTarget).ancestor('.accordion').one('.content').transition({easing:'ease-in',duration:.4,height:Y.one(e.currentTarget).siblings('.content').getAttribute('data-height'),paddingTop:'10px',paddingBottom:"10px"});
				}else{
					Y.one(e.currentTarget).ancestor('.accordion').one('.content').transition({easing:'ease-in',duration:.4,height:'0px',paddingTop:'0px',paddingBottom:'0px'});
					Y.one(e.currentTarget).ancestor('.accordion').removeClass('selected');
				}
				e.preventDefault();
			});
		}
	}, {
		NAME: 'MyNFL',
		ATTRS: {
			signInTemplate : {value:null},
			signedInTemplate : {value:null},
			newsTemplate : {value:null},	
			teamsInfo : {value:null},
			nextGameTemplate : {value:null} ,
			shopTemplate : {value:null},
			fantasySignInTemplate : {value:null},
			fantasySignedInTemplate : {value:null},
			fantasyMyTeams : {value:null},
			fantasyData : {value:null},
			accordionCheck : {value:0},
			omnitureModule : {value:null},
			facebookFriendActivitySignedInTemplate:{value:null},
			facebookFriendActivitySignInTemplate:{value:null},
			facebookRecommendTemplate:{value:null},
			facebookRecommendSignInTemplate:{value:null},
			moduleSelect:{value:null},
			moduleEnabled:{value:null},
			noTeam:{value:'<h3>NO TEAM</h3>'}
		}
	});
}, "3.1.1", { requires: ['widget','node','nfl-user','io-base','json','date','transition', 'nfl-user-fantasy','plucksdk','widget-fold','nfl-lang']});

