/* *
 * @author jcrane
 * @minify true
 */
var jQT = new $.jQTouch({
	// icon: 'jqtouch.png',
	statusBar: 'black-translucent',
	slideSelector: 'body > * > ul li a',
	preloadImages: [
		'http://media.star-telegram.com/static/scripts/jqtouch/themes/jqt/img/chevron_white.png',
		'http://media.star-telegram.com/static/scripts/jqtouch/themes/jqt/img/bg_row_select.gif',
		'http://media.star-telegram.com/static/scripts/jqtouch/themes/jqt/img/back_button_clicked.png',
		'http://media.star-telegram.com/static/scripts/jqtouch/themes/jqt/img/button_clicked.png'
	]
});
			
var mvst = {
	// create today, tomorrow, yesterday, next week and last week variables to be used in script queries
	// for teamplayer, to get last week's schedule, next week's schedule, and today's schedule
	calcDates: function() {
		var d = new Date(), 
			date = d.getDate(), 
			month = d.getMonth() + 1,
			year = d.getFullYear();
		this.today = month + '%2F' + date + '%2F' + year;
		d = this.resetDate();
		this.year = year;
		
		var tomorrow = d.setDate(d.getDate() + 1);
		tomorrow = new Date(tomorrow);
		var tomorrowDate = tomorrow.getDate(),
			tomorrowMonth = tomorrow.getMonth() + 1,
			tomorrowYear = tomorrow.getFullYear();
		this.tomorrow = tomorrowMonth + '%2F' + tomorrowDate + '%2F' + tomorrowYear;
		d = this.resetDate();
		
		var yesterday = d.setDate(d.getDate() - 1);
		yesterday = new Date(yesterday);
		var yesterdayDate = yesterday.getDate(),
			yesterdayMonth = yesterday.getMonth() + 1,
			yesterdayYear = yesterday.getFullYear();
		this.yesterday = yesterdayMonth + '%2F' + yesterdayDate + '%2F' + yesterdayYear;
		d = this.resetDate();
		
		var nextWeek = d.setDate(d.getDate() + 8);
		nextWeek = new Date(nextWeek);
		var nextDate = nextWeek.getDate(),
			nextMonth = nextWeek.getMonth() + 1,
			nextYear = nextWeek.getFullYear();
		this.nextWeek = nextMonth + '%2F' + nextDate + '%2F' + nextYear;
		d = this.resetDate();
		
		var lastWeek = d.setDate(d.getDate() - 8);
		lastWeek = new Date(lastWeek);
		var lastDate = lastWeek.getDate(),
			lastMonth = lastWeek.getMonth() + 1,
			lastYear = lastWeek.getFullYear();
		this.lastWeek = lastMonth + '%2F' + lastDate + '%2F' + lastYear;
	},
	// need to reset the date in the calcDates function each time we get a new date
	resetDate: function() {
		var d = new Date();
		return d;
	},
	// create the URL to be used by the getScript function
	createGetScript: function(getSport, schedule, tpl, divID, gameID, season) {
		var sports = mvst.sports, sportID;
		season = season || this.year;
		tpl = tpl || 'Schedule_Mobile';
		divID = schedule ? 'tp-' + getSport + '-' + schedule : 'tp-' + getSport + '-boxscore-' + gameID;
		// console.log('divID is ' + divID);
		for (var sport in sports) {
			if (sport == getSport) {
				sportID = sports[sport]['id'];
			}
		}
		var webPath = "http://fortworth-tpweb.newsengin.com/tpweb/web/",
			lastParams = 'gateway.php?mkt=&site=default&tpl=' + tpl + '&SearchType=Schedules&Sport=' + sportID + '&TeamID=&SchoolID=&DistrictID=&Season=' + season + '&SearchDate=' + this.lastWeek + '&SearchDateEnd=' + this.yesterday + '&Market=1&divID=' + divID + '&webPath=' + escape(webPath),
			nextParams = 'gateway.php?mkt=&site=default&tpl=' + tpl + '&SearchType=Schedules&Sport=' + sportID + '&TeamID=&SchoolID=&DistrictID=&Season=' + season + '&SearchDate=' + this.tomorrow + '&SearchDateEnd=' + this.nextWeek + '&Market=1&divID=' + divID + '&webPath=' + escape(webPath),
			todayParams = 'gateway.php?mkt=&site=default&tpl=' + tpl + '&SearchType=Schedules&Sport=' + sportID + '&TeamID=&SchoolID=&DistrictID=&Season=' + season + '&SearchDate=' + this.today + '&SearchDateEnd=' + this.today + '&Market=1&divID=' + divID + '&webPath=' + escape(webPath);
		switch (schedule) {
			case 'last7':
				return webPath + lastParams;
			case 'next7':
				return webPath + nextParams;
			case 'today':
				return webPath + todayParams;
			default: 
				return webPath + todayParams;
		}
	},
	football: function() {
		var sport = 'football',
			lastFootball = this.createGetScript(sport, 'last7'),
			nextFootball = this.createGetScript(sport, 'next7'),
			todayFootball = this.createGetScript(sport, 'today'),
			fScripts = [lastFootball, nextFootball, todayFootball];
			// console.log('in football func, nextFootball is ' + nextFootball);
		this.getScripts(fScripts, sport);
	},
	volleyball: function() {
		var sport = 'volleyball',
			lastVolleyball = this.createGetScript('volleyball', 'last7'),
			nextVolleyball = this.createGetScript('volleyball', 'next7'),
			todayVolleyball = this.createGetScript('volleyball', 'today'),
			vScripts = [lastVolleyball, nextVolleyball, todayVolleyball];
		this.getScripts(vScripts, sport);
	},
	baseball: function() {
		var sport = 'baseball',
			lastBaseball = this.createGetScript(sport, 'last7'),
			nextBaseball = this.createGetScript(sport, 'next7'),
			todayBaseball = this.createGetScript(sport, 'today'),
			fScripts = [lastBaseball, nextBaseball, todayBaseball];
		this.getScripts(fScripts, sport);
	},
	softball: function(){
		var sport = 'softball',
			lastSoftball = this.createGetScript(sport, 'last7'),
			nextSoftball = this.createGetScript(sport, 'next7'),
			todaySoftball = this.createGetScript(sport, 'today'),
			fScripts = [lastSoftball, nextSoftball, todaySoftball];
		this.getScripts(fScripts, sport);
	},
	boxscores : function() {
		$('.game-boxscore').live('click', function() {
			$this = $(this);
			var path = $this.children('a').attr('href');
			path = path.split('?')[1];
			src = 'http://fortworth-tpweb.newsengin.com/tpweb/web/gateway.php?' + path + '&divID=boxscore-game';
			$.getScript(src, function() {
				jQT.goTo('#boxscore');
				// $this.closest('.game-page').removeClass('current').siblings('#boxscore').addClass('current');
			});
			return false;
		});
		$('.game-boxscore').live('tap', function() {
			$this = $(this);
			var path = $this.children('a').attr('href');
			path = path.split('?')[1];
			src = 'http://fortworth-tpweb.newsengin.com/tpweb/web/gateway.php?' + path + '&divID=boxscore-game';
			$.getScript(src, function() {
				jQT.goTo('#boxscore');
				// $this.closest('.game-page').removeClass('current').siblings('#boxscore').addClass('current');
			});
			return false;
		});
		/* $('#boxscore-back').bind('tap click', function(){
              $('#boxscore').removeClass('current');
        }); */
	},
	
	/* callBoxscore : function() {
		$('.game-boxscore').children('a').click(function(e) {
			e.preventDefault();
			alert('callBoxscore');
			var href = $(this).attr('href');
			// href = href.split('?')[1];
			mvst.loadBoxscore(href);
		});
	},
	loadBoxscore : function(href) {
		$('#boxscore').bind('pageTransitionEnd', function(e, info){
	        // if (info.direction == 'in' && $(this).data('loaded') != 'true') {
				$(this).append($('<div>Loading&hellip;</div>'). 
					load(href, function(){
						path = href.split('?')[1];
						src = 'http://fortworth-tpweb.newsengin.com/tpweb/web/gateway.php?' + path + '&divID=boxscore-game';
						$.getScript(src);
					})
				); 
			// } 
		}); 
	}, */
	/* boxscores: function(sport){
		sport = this.utils.capFirst(sport);
		console.log(sport);
		var boxscoreLinks = $('.game-boxscore').map(function(){
			var path = $(this).children('a').attr('href');
			if (path) {
				path = path.split('?')[1];
				path = path.replace('tpl=Boxscore', 'tpl=Boxscore_Mobile');
				gameID = path.match(/ID=[0-9]+/)[0];
				gameID = gameID.replace('ID=', '');
				// $(this).children('a').attr('href', href);
				$(this).click(function(e){
					// console.log(e.target);
					var $target = ($(e.target));
					mvst.getBoxscore($target, path, gameID, sport);
					return false;
				})
			}
		});
	},
	getBoxscore: function($target, path, gameID, sport){
		if (!$target.data('loaded')) {
			// var divID = 'tp-' + sport + '-boxscore-' + id;
			// boxscoreDiv = $('<div id="' + divID + '"></div>').appendTo('body').append($('<div>Loading</div>'));
			// expected createGetScript params // getSport, schedule, tpl, divID, gameID, season
			var requestedBoxscore = mvst.createGetScript(sport, null, null, 'boxscore-game', gameID, null);
			// mvst.getScripts(requestedBoxscore);
		}
	}, */
	getScripts: function(allScripts, sport) {
		var allScriptsLen = allScripts.length;
		for (i = 0; i < allScriptsLen; i++) {
			// if (i !== (allScriptsLen - 1)) {
				$.getScript(allScripts[i]);
			// }
			// running boxscores on load instead of this slowness
			/* else {
				$.getScript(allScripts[i], function(){
					// mvst.getNumber(sport);
					mvst.boxscores(sport);
				});
			} */
		}
	},
	// as of 8-11-10, no longer calling this from anywhere b/c it was messing with loadAd function.
	// would love to figure out why and get this functionality back in place soon
	getNumber: function(sport) {
		// console.log('running getNumber() and the sport is ' + sport);
		var $gamePage, counter;
		$('.game-page').each(function(){
			$gamePage = $(this);
			var divID = $gamePage.attr('id');
			if ($gamePage.find('ul').length) {
				counter = $gamePage.find('ul').attr('data-count');
			}
			else {
				counter = '0';
			}
			$gamePage.data({
				counter: counter,
				divID: divID
			});
		});
		$gamePage.siblings('#' + sport).children('ul').find('a').each(function(){
			$this = $(this);
			// console.log($this);
			var href = $this.attr('href');
			// console.log(href);
			if (href != '#') {
				var divID = $(href);
				// console.log(divID);
				var counter = divID.data('counter');
				// console.log(counter);
				$this.parents('li').append('<small class="counter">' + counter + '</small>');
			}
		}); 
	},
	delayedInit: function() {
		/* $('#football-link').one('click', function(){
			mvst.football();
		}); */
		$('#volleyball-link').one('click', function(){
			mvst.volleyball();
		});
		$('#baseball-link').one('click', function(){
			mvst.baseball();
		});
		$('#softball-link').one('click', function(){
			mvst.softball();
		});	
		$('#headlines-link').one('click', function(){
			mvst.getNumber('headlines');
		});
	},
	init: function() {
		this.calcDates();
		this.delayedInit();
		this.callStory();
		this.football();
		this.boxscores();
		// this.callVideo();
		// this.footballNext7();
		// this.footballLast7();
	},
	utils: {
		// capitalize the first letter in a string
		capFirst : function(string) {
			return string.charAt(0).toUpperCase() + string.slice(1);
		}
	},
	callStory : function() {
		$('.headlines').children('ul').find('a').click(function() {
			href = $(this).href;
			mvst.loadStory(href);
		});	
	},
	loadStory : function(href) {
		$('#story').bind('pageTransitionEnd', function(e, info){ 
	        if (info.direction == 'in' && $(this).data('loaded') != 'true') 
				{
	                $(this).append($('<div>Loading&hellip;</div>'). 
						load(href, function(){
							$(this).parent().data('loaded', 'true'); 
                        })); 
				} 
		}); 
	},
	
	callVideo : function() {
		$('#videos').children('ul').find('a').click(function(event) {
			event.preventDefault();
			href = $(this).attr('href');
			$(this).attr('href','#video');
			// console.log(href);
			mvst.loadVideo(href);
		});	
	},
	loadVideo : function(href) {
		// console.log('in loadVideo function');
		$('#video').bind('pageTransitionEnd', function(e, info){ 
	        if (info.direction == 'in' && $(this).data('loaded') != 'true') 
				{
					vstVideo = document.getElementsByTagName('video')[0];
					// console.log('preparing to load video source');
	                vstVideo.src = href;
					vstVideo.load();
					vstVideo.play();
					$(this).parent().data('loaded', 'true');  
				} 
		}); 
	},
	loadTweets : function() {
		$('#twitter-link').one('click',function() {
			twst.getTweet('dfwvarsity',10,'varsity_twitter');
		});
	},
	refreshTweets : function() {
		$('.twitter-refresh').bind('click tap', function() {
			$('#varsity_twitter').empty(); // slideUp().
			twst.getTweet('dfwvarsity',10,'varsity_twitter');
		});
	},
	// this is an attempt to load the load the ads with ajax in the same way
	// they are loaded on galleries
	loadAd : function(ad_src, stats) {
		/* $('#football').bind('pageAnimationEnd', function(e, info){
			$this = $(this);
			console.log($this);
			console.log('this data ad is ' + $this.data('ad'));
			console.log('info.direction is ' + info.direction);
			// originally part of if statement below ... info.direction == 'in' && 
			if ($this.data('ad') != 'true')	
			{
				ad0 = new mvst.adInjector('300','50',ad_src,this,stats);
				ad0.injectAd();
				if (stats != undefined) {
					ad0.addStats();
				}
				$(this).data('ad', 'true');                      
			}
		}); */
		$('body > div:not(#home)').each(function() {
			$(this).bind('pageAnimationEnd', function(e, info){
				// console.log(e.target.id);
				$this = $(this);
				// console.log($this);
				// console.log($(this).data('referrer'));
				// console.log('this data ad is ' + $this.data('ad'));
				// console.log('info.direction is ' + info.direction);
				// originally part of if statement below ... info.direction == 'in' && 
				if ($this.data('ad') != 'true')	
				{
					ad0 = new mvst.adInjector('300','50',ad_src,this,stats);
					ad0.injectAd();
					if (stats !== undefined) {
						ad0.addStats();
					}
					$this.data('ad', 'true').unbind('pageAnimationStart');
				}
			});
		});
	/*	
		// this was original faked ad implemenation
		$adLink = $('#home .advertisement a').wrap('<div class="cloned-ad" />').clone();
		$clonedAd = $('.cloned-ad');
		console.log($clonedAd);
		$('body').children('div:not(#home)').bind('pageAnimationEnd', function(e, info){
	        if (info.direction == 'in' && $(this).data('ad') != 'true') 
			{ 
				$this = $(this);
				$(this).append($clonedAd);
				$(this).data('ad', 'true');                      
			} 
		});   */
	}, 
	adInjector : function(width, height, ad_src, container, stats) {
		this.ad = document.createElement('IFRAME');
		this.ad.width = width ? width : '300';
		this.ad.height = height ? height : '250';
		this.ad.scrolling = 'no';
		this.ad.frameBorder = '0';
		// this.ad.marginheight = '0';
		// this.ad.marginwidth = '0';
		this.ad.src = ad_src;
		this.ad.style.display = 'none';
		this.container = container;
		this.stats = stats;
		// hiding this iframe on load b/c of flash of white background as iframe src loads (waiting on ad server)
		mvst.showAd(this.ad);
		// console.log('this.stats in adInjector() is ' + this.stats);
	},
	// called from mvst.adInjector(), passed the iframe as a parameter
	showAd : function(ad) {
		// when the iframe content loads
		ad.onload = function() {
			// display it
			ad.style.display = 'block';
		};
	}
	
};
		
mvst.adInjector.prototype.injectAd = function() {
	$(this.container).append(this.ad); // .addClass('injected');
};
mvst.adInjector.prototype.addStats = function() {
	if (this.stats !== undefined) {
		s.pageName = "AJAX: " + mistats.pagename;
		mistats_resend();
		s.pageName = null;
	}
};
// sport IDs are generated by teamplayer
mvst.sports = {
	'football' : {
		'id' : '1'	
	},
	'volleyball' : {
		'id' : '10'
	},
	'baseball' : {
		'id' : '29'
	},
	'softball' : {
		'id' : '30'
	}
};
