var t1CurrentSlideId = 0;
var t1PreviousSlideId = 0;
var t1NextSlideId = 0;
var blnT1Rotate = true;
var t1SlideCount = 0;
var t1SlideDelay = 15000;
var isSwitching = false;

var t1Debug =  false; // Shows details in the status bar and hides the ads.
// Rotating T1 Code
// 	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-	-
// 

// 1/8/2009 - John Jimenez
// RE: Request from Tia Likely to investigate why the Pause, Next, & Previous
//     functions stopped working.


function slideshowInit() {
	t1SlideCount = $$('#tourTournT1Box .tourTournT1ViewPort').length;
	
	t1CurrentSlideId = 1;
	t1NextSlideId = 2;
	t1PreviousSlideId = t1SlideCount;

	// Only do the slideshow if more than one slide.
	if (t1SlideCount > 1) { start_slideshow(1, t1SlideCount, t1SlideDelay); }
	else {if ($('tourTournT1Controls')) { $('tourTournT1Controls').hide(); }} // hide the controls otherwise;

}


function start_slideshow(firstFrame, lastFrame, delay) {
	// Store The First, Last & Delay into globals for ease of use
	// Force the blnT1Rotate flag to true
	// set strSlideShowString to the string that will be eval()ed by setTimeout
	t1Delay = delay;
	t1FirstFrame = firstFrame;
	t1CurrentFrame = firstFrame;
	t1LastFrame = lastFrame;

	blnT1Rotate = true;
	t1IsPaused = !blnT1Rotate;
	if (firstFrame != lastFrame)	{
		PlaySlide();
	}
	
}

// Switches the slides visually
function switch_slide(hideFrame, showFrame, delay) {
	// Check the Flag. True means Rotate; False, not so much.
	if (blnT1Rotate && t1SlideCount) {
		isSwitching = true;
		clearTimeout(tour_slideshow);
		// Fade out current frame
		Effect.Fade('tourT1ViewPort' + hideFrame);
		// Switch the frames around (copy/pasted from old code, formated & variables changed)
		if (showFrame > t1LastFrame) {
			showFrame = t1FirstFrame;
		} else if (showFrame < t1FirstFrame) {
			showFrame = t1LastFrame;
		}
		t1CurrentFrame = showFrame;
		setTimeout("Effect.Appear('tourT1ViewPort" + showFrame + "');", 850);
		isSwitching = false;
		PlaySlide();
	}
	if (t1Debug)  { slideshow_debug_status(); }
}

// Starts the timer for the next slide
function PlaySlide() {
	blnT1Rotate = true;
	strSlideShowString = 'switch_slide('+t1CurrentFrame+','+(t1CurrentFrame+1)+','+t1Delay+');';
	tour_slideshow = setTimeout(strSlideShowString, t1Delay + 850);
	if (t1Debug)  { slideshow_debug_status(); }
}

// Toggle, Next, & Previous will only work if start_slideshow was called.
function ToggleSlideShow() {
	if (t1CurrentFrame) {
		if (!t1IsPaused) { pauseSlide() }
		else { unpauseSlide() }
	}
	if (t1Debug)  { slideshow_debug_status(); }
}

function pauseSlide() {
	//blnT1Rotate = false;
	t1IsPaused = true;
	clearTimeout(tour_slideshow);
	if (!t1IsPaused) { ToggleSlideShow() }
	if (t1Debug)  { slideshow_debug_status(); }
}

function unpauseSlide() {
	//blnT1Rotate = true;
	t1IsPaused = false;
	PlaySlide();
	if (t1Debug)  { slideshow_debug_status(); }
}

function NextSlide() {
	if (t1CurrentFrame && !isSwitching) {
		clearTimeout(tour_slideshow);
		switch_slide(t1CurrentFrame, t1CurrentFrame+1, t1Delay);
		pauseSlide();
	}
	if (t1Debug)  { slideshow_debug_status(); }
}

function PreviousSlide() {
	if (t1CurrentFrame && !isSwitching) {
		clearTimeout(tour_slideshow);
		switch_slide(t1CurrentFrame, t1CurrentFrame-1, t1Delay);
		pauseSlide();
	}
	if (t1Debug)  { slideshow_debug_status(); }
}

function slideshow_debug_status(){
	var statMsg = 'cS: '+t1CurrentFrame;
	statMsg += ' | P: '+t1IsPaused;
	window.status = statMsg;
}

function slideshow_debug() {
	var msg = 'SlideShow Debug\n\n';
	msg += 'strSlideShowString = '+strSlideShowString+'\n';
	msg += 't1CurrentFrame = '+t1CurrentFrame+'\n';
	msg += 't1Delay = '+t1Delay+'\n';
	msg += 't1FirstFrame = '+t1FirstFrame+'\n';
	msg += 't1LastFrame = '+t1LastFrame+'\n';
	msg += 'blnT1Rotate = '+blnT1Rotate+'\n';
	msg += 't1IsPaused = '+t1IsPaused +'\n';
	alert(msg);
}

function showHideSlides (showHide) {

	if (showHide) { showHide = showHide.toLowerCase(); }

	switch (showHide) {
		case 'show':
			$('tourTournT1VideoContainer').addClassName('videoHide');
			$('tourT1ViewPort'+t1CurrentFrame).removeClassName('hide');
			$('tourTournT1Controls').removeClassName('hide');
			$$('#tourTournT1Box .tourTournBlackBox')[0].removeClassName('hide');
			
			break;
		default:
			$('tourT1ViewPort'+t1CurrentFrame).addClassName('hide');
			$('tourTournT1Controls').addClassName('hide');
			$$('#tourTournT1Box .tourTournBlackBox')[0].addClassName('hide');
			$('tourTournT1VideoContainer').removeClassName('videoHide');
			break;
	}
}

function keyStatsSetup(tID) {
	keyStats = false;
	new Ajax.Request('/.element/ssi/auto/3.0/sdms/tournaments/'+tID+'/stats/current/keyStats_body.json', {
		method: 'get',
		asynchronous: false,
		onSuccess: function(transport) { keyStats = transport.responseText.evalJSON(true).tour; }
	});
	if (keyStats != false) {

		// Toughest / Easiest Holes:
		teHoles = $$('#tourTournKeyStatsCont .tourKeyStatsHoleData .tourKeyStatsHoleDataLI');
		teHoles[0].innerHTML = keyStats.toughhole.value; // tough
		teHoles[1].innerHTML = keyStats.easyhole.value; // easy

		keyStats.stat.each(function(s){
			// First figure out which stat to target.
			var theID = '';
			switch (s.nm.toLowerCase()) {
				case "scoring average (actual)":
					theID = 'tourKeyStatScoringAve';
					break;
				case "driving distance":
					theID = 'tourKeyStatDrivingDis';
					break;
				case "driving accuracy":
					theID = 'tourKeyStatDrivingAcc';
					break;
				case "greens in regulation":
					theID = 'tourKeyStatGreensReg';
					break;
				default:
					return;
			}
			if (theID != '') {
				// Get the Player's Data ready
				idArr = ('0'+s.leader.player.id).toArray();
				idPath = idArr[0]+idArr[1]+'/'+idArr[2]+idArr[3]+'/'+idArr[4]+idArr[5];
				
				// Now populate the data in that target
					// Headshot
				$$('#'+theID+' .tourPlayerHeadshot72x82 img')[0].src="http://i.cdn.turner.com/pgatour/players/"+idPath+"/images/headshot-72x82.jpg";
					// Player Name
				$$('#'+theID+' .pName')[0].innerHTML = s.leader.player.fn.charAt(0)+'. '+s.leader.player.ln;
					// Player Score
				$$('#'+theID+' .pVal')[0].innerHTML = s.leader.score.replace('%','');
					// Average Score
				$$('#'+theID+' .aVal')[0].innerHTML = s.average.replace('%','');
			}
		});

	}
}

function lbSetup() {
	myTop5Holder = [];
	$$('#tourTournLB10 .tourStandingsLive')[0].replace(getLBTable(tourn_id));
}

function timestamp() {
	var n, y, M, d, h, m, s;

	n=new Date();
	y=n.getFullYear();
	M=n.getMonth()+1;
	d=n.getDate();
	h=n.getHours();
	m=n.getMinutes();
	s=n.getSeconds();

	if(M<10) M='0'+M;
	if(d<10) d='0'+d;
	if(h<10) h='0'+h;
	if(m<10) m='0'+m;
	if(s<10) s='0'+s;

	return y+M+d+h+m+s;
}

function getLBTable (tID) {
	if (typeof myTop5Holder[tID] == 'undefined') {
		myTop5Holder[tID] = timestamp();
	}
	var output = '<table class="tourStandingsLive">\n\t<tr class="topRow"><td class="rank">RANK</td><td class="name">PLAYER</td><td class="day">TODAY</td><td class="thru">THRU</td><td class="tot">TOTAL</td></tr>\n';
	var theScore = {};

	// Grab the JSON and assign it to theScore
	new Ajax.Request('/.element/ssi/auto/3.0/sdms/data/leaderboards/'+tID+'/current/top10LB.json?'+myTop5Holder[tID], {
		method: 'get',
		asynchronous: false,
		onSuccess: function(transport) { theScore = transport.responseText.evalJSON(true); }
	});
	if (theScore.leaderboard) {
		pCnt = theScore.leaderboard.eventInfo.p.length;
		for (var i=0; i<pCnt; i++) {
			var thisPlayer = theScore.leaderboard.eventInfo.p[i];
			thisClass = ((i+1)%2)? 'odd':'even'
			output += '\t<tr class="'+thisClass+'"><td class="rank">'+thisPlayer.cPos+'</td><td class="name">'+thisPlayer.fName+' '+thisPlayer.lName+'</td><td class="day">'+thisPlayer.pDay+'</td><td class="thru">'+thisPlayer.thru+'</td><td class="tot">'+thisPlayer.pTot+'</td></tr>\n';
		}
		output += "</table>";
		myTop5Holder[tID] = theScore.leaderboard.cts;
		return output;
	}
}

function pageInit() {
	thisPage = document.location.pathname.toLowerCase().replace('/index.html','').replace(/\/$/,'');
	switch (thisPage) {
		case "/tournaments/r011":
		case "/.devel/jjimenez/theplayers": // Testing location, can be removed once we go live.
			slideshowInit();
			keyStatsSetup(tourn_id);
			lbSetup();
			break;
		default:
	}


}

// Fire Events
document.observe('dom:loaded', pageInit);

