nfl.namespace('nfl.data.live');
nfl.namespace('nfl.global.live');
nfl.namespace('nfl.ui.live');
/*
 * @author arianna.winters
 * @class nfl.data.live.Game
 * @param {Object} gameScheduleData
 * @requires teams.json as nfl.data.Teams
 */
nfl.data.live.Game	= Class.create(
	{
		initialize:function(gameScheduleData){
			/* mix in the schedule data with this objects properties */
			Object.extend(this,gameScheduleData);
			/* create an extended date object and assign to self.date */
			//var dateObj	= new Date(this.date);
			var dateExtended = {week:this.week, dayName:this.dayName,displayString: this.date};
			this.date	= dateExtended;
			nfl.log("game data:\n"+ Object.toJSON(this));
			/* create game link */
			this.href = {open:('<a href=\"/'+this.liveEvent+'" class="live-schedule-watch-link">'),text:'Watch Live Online',close:'</a>'};			
			if(this.liveEvent == 'live'){
				this.href.text	= 'Online Extra';
			}
			if(this.capaignCodes){
				this.href.open	= ('<a href=\"/'+this.liveEvent+'?icampaign='+ this.capaignCodes[this.liveEvent] +'\" class="live-schedule-watch-link">');
			}
			/* extend home and visiting team object with static team data */
			try{
				Object.extend(this.homeTeam, nfl.data.Teams[this.homeTeam.abbr]);
				Object.extend(this.visitingTeam, nfl.data.Teams[this.visitingTeam.abbr]);
				this.homeTeam.cityState = (this.homeTeam.city == 'New York')?this.homeTeam.displayName:this.homeTeam.city;
				this.visitingTeam.cityState = (this.visitingTeam.city == 'New York')?this.visitingTeam.displayName:this.visitingTeam.city;
				this.homeTeam.logo 		= "<img src=\""+ nfl.global.imagepath + this.homeTeam.mediumLogo +"\"/>";
				this.visitingTeam.logo	= "<img src=\""+ nfl.global.imagepath + this.visitingTeam.mediumLogo +"\"/>";
				this.homeTeam.href		= {open:("<a href=\""+ nfl.data.Teams[this.homeTeam.abbr].teamPage +"\" class=\"live-schedule-team-link\">"),close:"</a>"};
				this.visitingTeam.href	= {open:("<a href=\""+ nfl.data.Teams[this.visitingTeam.abbr].teamPage +"\" class=\"live-schedule-team-link\">"),close:"</a>"};
				
			}catch(e){nfl.log('error extending team objects: '+e.message);}
		},
		getHomeTeam:function(){ return this.homeTeam },
		getHomeTeamId:function(){ return this.getHomeTeam().id },
		getHomeTeamLinkName:function(){ return this.getHomeTeam().displayName.toLowerCase().replace(' ','') },
		getHomeTeamLink:function(){ return this.getHomeTeam().url },
		getVisitorTeam:function(){ return this.visitingTeam },
		getVisitorTeamId:function(){ return this.getVisitingTeam().id },
		getVisitorTeamLinkName:function(){ return this.getVisitingTeam().displayName.toLowerCase().replace(' ','') },
		getVisitorTeamLink:function(){ return this.getVisitingTeam().url }
	}
);
/*
 * @author arianna.winters
 * @class nfl.data.live.Schedule
 * @param {Object} json 
 * @param {Object} options
 * @requires nfl.data.live.Game
 */
nfl.data.live.Schedule	= Class.create({
	initialize: function(json,options){
		this.displayMode		= options.displayMode || 'all';
		this.defaultMode		= options.defaultMode || 'current-game';
		this.capaignCodes		= options.capaignCodes || null;
		this.currentWeek		= json.currentWeek;
		this.pagingValue		= 0;
		this.filtersOperator	= '&&';
		this.pagingIncrementMultiplyer	= 1;
		this.pagingIndexes		= [];
		this.pagingLimit		= 0;
		this.__gameDataSet	= json.GameSchedules;
		if(this.__gameDataSet.size() == 0){
			document.fire('nfl:live:schedule:nodata');
		}
		/* run through games and extend */
		this.__gameDataSet.each(function(game,index){
			if(this.capaignCodes != null){ Object.extend(game,{'capaignCodes':this.capaignCodes}); }
			this.__gameDataSet[index]		= new nfl.data.live.Game(game);
			this.__gameDataSet[index].index = index;
		}.bind(this));
		this.games			= this.__gameDataSet;
		if(this.__gameDataSet.size() > 0){
			switch(this.displayMode){
				case 'by-week':
					/* set current filter to current week */
					this.filters	= [{field:'week',value:this.currentWeek}];
					this.pagingValue = this.currentWeek;
					break
				case 'by-two':
					/* set current filter to current week */
					this.__gameDataSet.each(function(game,index){
						if(game.week >= this.currentWeek){ 
							this.pagingValue = game.index;
							throw $break;
						}
					}.bind(this));
					this.filtersOperator	= '||';
					this.filters			= [{field:'index',value:this.pagingValue},{field:'index',value:(this.pagingValue+1)}];
					this.pagingIncrementMultiplyer	= 2;
					break
				case 'tnf-current':
					this.filters	= [{field:'liveEvent',value:'live'},{field:'status',value:'NOT_YET_PLAYED'}];
					this.pagingValue = null;
					break
				default:
					this.filters = null;
					break
			}
			/* get the highest paging value number, assign it to pagingLimit */
			if(this.pagingValue != null && this.filters != null){
				this.__gameDataSet.each(function(game,index){
					//check paging value field
					if(this.displayMode == 'by-week'){ if(game.week > this.pagingLimit){ this.pagingLimit = game.week;}}
					if(this.displayMode == 'by-two'){ this.pagingLimit = index; }
				}.bind(this));
			}
			this.applyFilters();
		}
	},
	applyFilters: function(){
		if(this.filters != null){
			//nfl.log('nfl.data.live.Schedule.applyFilters: this.filtersOperator = '+ this.filtersOperator);
			var __filteredDataSet	= [];
			this.__gameDataSet.each(function(gameObj,rowindex){
				//nfl.log('nfl.data.live.Schedule.applyFilters: iterating over item '+ rowindex +' in this.__gameDataSet');
				var rowItem		= gameObj;
				var appendRow	= (this.filtersOperator == '&&')?true:false;
				/* there's gotta be a better way to do this, no time to think about it */
				this.filters.each(function(filter,filterindex){
					//nfl.log('nfl.data.live.Schedule.applyFilters: iterating over filter '+ filterindex +' in this.filters');
					if(typeof rowItem[filter.field] != "undefined"){
						if(rowItem[filter.field] != null){
							if(this.filtersOperator == '&&'){
								if(typeof rowItem[filter.field] == "number" && rowItem[filter.field] != filter.value){ appendRow = false; }
								if(typeof rowItem[filter.field] == "string" && rowItem[filter.field].toUpperCase() != filter.value.toUpperCase()){ appendRow = false; }
							}else{
								/* must be or */
								if(typeof rowItem[filter.field] == "number" && rowItem[filter.field] == filter.value){ appendRow = true; }
								if(typeof rowItem[filter.field] == "string" && rowItem[filter.field].toUpperCase() == filter.value.toUpperCase()){ appendRow = true; }
								if(appendRow) return true
							}
							//nfl.log("tested "+ rowItem[this.filters[filterindex].field] +" against '"+ this.filtersOperator +"' on "+ this.filters[filterindex].value +" which is of type \""+ (typeof rowItem[this.filters[filterindex].field])+"\"");
						}else{
							/* field is null, automatically fail */
							appendRow = false;
						}
					}else{
						/* does not have property, criteria check automatically fails */
						appendRow = false;
					}
					if(!appendRow && this.filtersOperator == '&&') return true
				}.bind(this));					
				if(appendRow){
					__filteredDataSet[__filteredDataSet.length]	= gameObj;
				}
			}.bind(this));
			this.games	= __filteredDataSet;
		}else{
			nfl.log('nfl.data.live.Schedule.applyFilters: no filters present.');
			this.games	= this.__gameDataSet;
		}
	},
	next: function(){
		this.pagingValue = (this.pagingValue + (1*this.pagingIncrementMultiplyer));
		nfl.log('nfl.data.live.Schedule.next: '+ this.displayMode +': '+this.pagingValue);
		switch(this.displayMode){
			case 'by-week':
				this.filters	= [{field:'week',value:this.pagingValue}];
				break;
			case 'by-two':
				this.filters	= [{field:'index',value:this.pagingValue},{field:'index',value:(this.pagingValue+1)}];
				break;
			default:
				this.filters = null;
		}
		this.applyFilters();
		if(this.games.size() == 0 && this.pagingValue < this.pagingLimit){ this.next(); return;} /* try again (DANGEROUS) */
		this.write();
	},
	previous: function(){
		this.pagingValue = (this.pagingValue - (1*this.pagingIncrementMultiplyer));
		nfl.log('nfl.data.live.Schedule.previous: '+ this.displayMode +': '+this.pagingValue);
		switch(this.displayMode){
			case 'by-week':
				/* set current filter to current week */
				this.filters	= [{field:'week',value:this.pagingValue}];
				break;
			case 'by-two':
				this.filters	= [{field:'index',value:this.pagingValue},{field:'index',value:(this.pagingValue+1)}];
				break;
			default:
				this.filters = null;
		}
		this.applyFilters();
		if(this.games.size() == 0 && this.pagingValue > 1){ this.previous(); return;} /* try again */ 
		this.write();
	},
	write: function(containerId,templates){
		nfl.log('nfl.data.live.Schedule.write');
		if (!this.containerId) { this.containerId = containerId; }
		if (!this.templates) { this.templates = templates; }
		/* get schedule container object */
		this.container		= $(this.containerId);
		//nfl.log('nfl.data.live.Schedule.write: this.__gameDataSet size = '+ this.__gameDataSet.size());
		//nfl.log('nfl.data.live.Schedule.write: this.games size = '+ this.games.size());
		if(this.__gameDataSet.size() > 0){
			/* merge templates with data */
				/* merge repeating row data first */
				var rowContent		= '';
				var rowTemplate		= new Template(this.templates['row'].replace('row-template',''));
				this.games.each(function(game,index){
					rowContent += rowTemplate.evaluate(game);
				});
				/* merge in other data */
				var retContentObject	= {currentWeek: this.currentWeek, rows: rowContent};
				var retContentTemplate	= new Template(this.templates['body']);
				var updatedContent		= retContentTemplate.evaluate(retContentObject);
			/* update container with templated content */
			this.container.update(updatedContent);
			/* add hard psuedo classes */
			try{
				this.container.select('.row')[0].addClassName('first-row');
			}catch(e){}
		}
	}
});

nfl.namespace('nfl.ui.live.landing');
/* this are quick-dirty ports of the zipcode check function in the network section */
/* yes I know these should not be in a file with "nfl.data" as the namespace file name convention */
nfl.ui.live.landing.enableCheckZipCode	= function(){
	$('tnf-landing-form-get-nfln-submit').disabled	= true;
	if($('tnf-landing-form-get-nfln-zipcode').value.length==5){
		if(nfl.ui.live.landing.isInteger($('tnf-landing-form-get-nfln-zipcode').value))
			$('tnf-landing-form-get-nfln-submit').disabled=false;
	}
}
nfl.ui.live.landing.isInteger			= function(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

nfl.namespace('nfl.ui.live.landing.schedule');
/*
 * @author arianna.winters
 * @handler nfl.ui.live.landing.schedule.onScroll
 * @requires prototype.js
 * @requires effects.js
 */
nfl.ui.live.landing.schedule.onScroll = function(event){
	nfl.log("{nfl.ui.live.landing.schedule.onScroll: id="+ event.memo.id +"}");
	var amountToScroll	= 0;
	direction 		= event.memo.direction;
	itemcontainer	= $(event.memo.id);
	portwidth 		= itemcontainer.up().getWidth();
	try{ 
		var itemLeft	= parseInt(itemcontainer.getStyle('margin-left'));
	}catch(e){
		itemcontainer.setStyle({'margin-left':'0px'});
		var itemLeft	= parseInt(itemcontainer.getStyle('margin-left'));
	}
	switch(direction){
		case 'left':
			amountToScroll	= (itemLeft == 0)?0:(amountToScroll + portwidth);
			break;
		case 'right':
			amountToScroll	= ((itemLeft + (0 - portwidth)) <= (0 - parseInt(itemcontainer.getStyle('width'))))?0:(amountToScroll - portwidth);
			nfl.log('('+ (itemLeft + (0 - portwidth)) +' <= (0 - '+ parseInt(itemcontainer.getStyle('width')) +') ? '+ ((itemLeft + (0 - portwidth)) <= (0 - parseInt(itemcontainer.getStyle('width')))));
			break;
		default:
			break;
	}
	nfl.log("{nfl.ui.live.landing.schedule.onScroll: amountToScroll = "+ amountToScroll +"}");
	//now perform scroll operation based on value outputs from switch statement above
	if(itemLeft % portwidth == 0){
		newLeft	= (itemLeft + amountToScroll);
		nfl.log("{nfl.ui.live.landing.schedule.onScroll: newLeft = "+ newLeft +"}");
		$(itemcontainer).morph('margin-left: ' + newLeft + 'px;',{afterFinish: nfl.ui.live.landing.schedule.afterScroll});
		nfl.log("{nfl.ui.live.landing.schedule.onScroll: "+ event.memo.id +" morph started ");
	}else{
		nfl.log("{nfl.ui.live.landing.schedule.onScroll: item is in play: "+ itemLeft +" % "+ portwidth +" = "+ (itemLeft % portwidth) +"}");
	}
}
/*
 * @author arianna.winters
 * @handler nfl.ui.live.landing.schedule.afterScroll
 * @requires prototype.js
 */
nfl.ui.live.landing.schedule.afterScroll = function(event){
	nfl.log("{nfl.ui.live.landing.schedule.afterScroll}");
	/* disable or enable scroll buttons */
	var itemcontainer	= $('live-schedule-all');
	var itemLeft		= parseInt(itemcontainer.getStyle('margin-left'));
	var portwidth 		= itemcontainer.up().getWidth();
	nfl.log("{nfl.ui.live.landing.schedule.afterScroll: itemLeft = "+ itemLeft +"}");
	if($(itemcontainer).getWidth() <= portwidth){
		/* hide scroll arrows since there's only one pane */
		$('tnf-landing-scroller-button-left').addClassName('hidden');
		$('tnf-landing-scroller-button-right').addClassName('hidden');
		return
	}
	if(itemLeft == 0){
		/* disable left arrow */
		$('tnf-landing-scroller-button-left').addClassName('disabled');
	}else{
		/* enable left arrow */
		$('tnf-landing-scroller-button-left').removeClassName('disabled');
	}
	if(((itemLeft + (0 - portwidth)) <= (0 - parseInt(itemcontainer.getStyle('width'))))){
		/* disable right arrow */
		$('tnf-landing-scroller-button-right').addClassName('disabled');
	}else{
		/* enable right arrow */
		$('tnf-landing-scroller-button-right').removeClassName('disabled');
	}
}

nfl.namespace('nfl.ui.live.home.schedule');
/*
 * @author arianna.winters
 * @handler nfl.ui.live.home.schedule.onPagingClick
 * @requires prototype.js
 * @requires nfl.global.live.schedule
 */
nfl.ui.live.home.schedule.onPagingClick = function(event){
	/* adjust the results */
	nfl.log('nfl.ui.live.home.schedule.onPagingClick');
	var ele	= Event.element(event);
	var direction = '';
	if(ele.id == 'live-schedule-button-left'){ direction = 'left';}
	if(ele.id == 'live-schedule-button-right'){ direction = 'right';}
	if(direction == 'left' && nfl.global.live.schedule.pagingValue > 1){ nfl.global.live.schedule.previous();} /* go back a week */
	if(direction == 'right' && nfl.global.live.schedule.pagingValue < nfl.global.live.schedule.pagingLimit){ nfl.global.live.schedule.next();} /* go forward a week */
	/* doing the check afterward because previous/next methods make skip empty increment filter values */
	if(nfl.global.live.schedule.pagingValue == 1){ $('live-schedule-button-left').addClassName('disabled'); /* disable back button (visually)*/ }else{ $('live-schedule-button-left').removeClassName('disabled'); /* enable back button (visually) */ }
	if(nfl.global.live.schedule.pagingValue == nfl.global.live.schedule.pagingLimit){ $('live-schedule-button-right').addClassName('disabled'); /* disable forward button (visually)*/ }else{ $('live-schedule-button-right').removeClassName('disabled'); /* enable forward button (visually) */ }
	/* stop event */
	Event.stop(event);
}