var sp_debugger = ''; // Debug message holder.

function switchStandingsTab(key) {

	// Set up the times for this tour
	doStandingsTimes(key);

	// Change the Tab
	tabsArr = $$('#tourStandingsTabSet .active');
	if (tabsArr.length){ tabsArr[0].removeClassName('active'); }
	if ($('tourStandingsTab'+key)) { $('tourStandingsTab'+key).addClassName('active'); }

	// Swap the content
	contentArr = $$('#tourStandingsContentContainer .tourStanding');
	if (contentArr){
		contentLen = contentArr.length;
		for (var i=0; i<contentLen; i++) {
			if (contentArr[i].id == 'tourStandingsContent'+key) {
				contentArr[i].removeClassName('hide');
			} else if (!contentArr[i].hasClassName('hide')) {
				contentArr[i].addClassName('hide');
			}
		}

		// Now, handle the LB.
		// We are handling the LB on the switch to:
		// a) Avoid Loading data when the user has not asked for it.
		// b) Allow us to turn the LIVE updating off for tabs we are not currently viewing.

		// First Kill all Live LBs
		killLiveLBs(key.toLowerCase());

		// Now do the LBs
		switch (key.toLowerCase()) {
			case 'r': doLB(rTs); break;
			case 's': doLB(sTs); break;
			case 'h': doLB(hTs); break;
			default: break;
		}
	}
	
}


// This function is run once for each CMS JSON (1 per tour)
function handleCMSTournData (cmsObj) {
	var addLive = '';
	for (var i=0, cmsObjLen = cmsObj.length; i<cmsObjLen; i++) {
		var thisObj = cmsObj[i];
		var theHTMLID = 'tourStandings_' + thisObj.rendererID; //thisObj.tID;

		if ($(theHTMLID)) { // Only do these if the HTML obj exists
			// Do the Title
			// Adjust the Title
			if (thisObj.isLive) {
				addLive = '<span class="tourHPLIVEFlag">LIVE&nbsp;</span>';
				if (thisObj.title.length > 40) {
					addStyle = 'style = "font-size:17px !important;"';
				} else { addStyle=""; }
			} else {
				addStyle= "";
				addLive = '';
			}
			$$('#'+theHTMLID+' .tourStandingsTitle')[0].innerHTML = '<a href="/tournaments/'+thisObj.tID+'/" '+addStyle+'>'+addLive+thisObj.title+'</a>';

			// Do the Links
			var output = '<h3>'+thisObj.linksHeader+'</h3><ul>';
			for (var j=0, lCnt=thisObj.links.length; j<lCnt; j++) {
				output += '<li><a href="'+thisObj.links[j].url+'">'+thisObj.links[j].text+'</a></li>';
			}
			output += '</ul>';
			$$('#'+theHTMLID+' .tourStandingsActiveLinks')[0].innerHTML = output;
			/* need to come up with the proper path this is space holder for now */
			$$('#'+theHTMLID+' .tourStandingsLogo')[0].innerHTML = '<a href="/tournaments/'+thisObj.tID+'/"><img src="http://i.cdn.turner.com/pgatour' + thisObj.logo + '" border="0"/></a>';

			// Override Image / Override Link
			if (thisObj.orImage){
				output = '<img src="'+thisObj.orImage+'" class="tourStandingsContentRightORImg" />';
				if (thisObj.orImageLink){ output =  '<a href="'+thisObj.orImageLink+'" target="_blank">'+output+'</a>'; }
				$$('#'+theHTMLID+' .tourStandingsTableContainer')[0].innerHTML = output;
			}

			// By-pass the standard standings / top5 code with an Override URL
			// This will be highly experimental!
			if (thisObj.orURL) {
				new Ajax.Request(thisObj.orURL, {
					method: 'get',
					parameters:'random='+Math.random(),
					asynchronous: false,
					onSuccess: function(transport) { $$('#'+theHTMLID+' .tourStandingsContentRight')[0].innerHTML = transport.responseText; }
				});
			}
		}
	}
}

function killLiveLBs () { for (var i=0,lCnt=tourLiveLBs.length; i<lCnt; i++) { clearTimeout(eval(tourLiveLBs[i])); } }

function doLB (cmsObj) {
	window.pbAdDone = (window.pbAdDone)? true:false;
	for (var i=0, cmsObjLen = cmsObj.length; i<cmsObjLen; i++) {
		var thisObj = cmsObj[i];
		var tour = thisObj.tID.substring(0,1).toLowerCase();
		var theHTMLID = 'tourStandings_' + thisObj.rendererID; //thisObj.tID;
		var footerLink = footerText = '';
		// If we are in leaderboard mode, grab the Top5LB
		if (thisObj.leaderboard == 'leaderboard') {
			$$('#'+theHTMLID+' .tourStandingsTableContainer')[0].innerHTML = getLBTable(thisObj.tID);
			if (tour == 'r') {
				if (i>0) { // For the 2nd tournament we want to go to their LB
					$$('#'+theHTMLID+' .tourStandingsContentRightFullLBLink')[0].innerHTML = '<a href="/leaderboards/current/'+thisObj.tID+'" class="tourStandingsLink">Full Leaderboard</a> <!-- '+i+' -->';
				} else {
					$$('#'+theHTMLID+' .tourStandingsContentRightFullLBLink')[0].innerHTML = '<a href="/r/leaderboard" class="tourStandingsLink">Full Leaderboard</a> <!-- '+i+' -->';
				}
				
			} else {
				$$('#'+theHTMLID+' .tourStandingsContentRightFullLBLink')[0].innerHTML = '<a href="/leaderboards/current/'+thisObj.tID+'" class="tourStandingsLink">Full Leaderboard</a> <!-- '+i+' -->';
			}

			// Only refresh if the LB is live.
			if (thisObj.isLive) {
				tourLiveLBs.push('timer_'+thisObj.tID);
				evalStr = 'timer_'+thisObj.tID+'= setInterval("$$(\'#'+theHTMLID+' .tourStandingsTableContainer\')[0].innerHTML = getLBTable(\''+thisObj.tID+'\');",'+(tourLiveLBTimer*1000)+')';
				eval(evalStr);
			}

			// Ticket PGATOUR-8345
			// Adjust the homepage 91x20 so that is shows up whenever the leaderboard data is on the homepage. Doesn't matter if the tournament is live or not.
			// OLD IF Statement (in case of rollback request)
			//if (thisObj.rendererID.match(theCurrentTour.toUpperCase()) && pbAdDone == false && thisObj.isLive == true) {
			if (thisObj.rendererID.match(theCurrentTour.toUpperCase()) && window.pbAdDone == false) {
				window.pbAdDone = true;
				$$('#'+theHTMLID+' .tourPoweredByIF')[0].src = '/.element/ssi/sect/5.0/'+theCurrentTour+'/91x20_ad.html';
				if (!IE) {
					$$('#'+theHTMLID+' .tourPoweredByIF')[0].contentWindow.location.reload(1);
				}
			}
			
		} else { // Otherwise we grab the tour Standings.
			if ($$('#'+theHTMLID+' .tourStandingsTableContainer')) { // There is a table container
				if ($$('#'+theHTMLID+' .tourStandingsTableContainer')[0].innerHTML == '') { // and it is empty.
					switch (tour) {
						case 'r':
							//footerLink = '/r/stats/info/?02394';
							footerLink = '/r/stats/info/?02395';
							footerText = 'FedExCup Points Standings';
							break;
						case 's':
							footerLink = '/s/stats/info/?193';
							footerText = 'Complete Charles Schwab Cup Points';
							break;
						case 'h':
							footerLink = '/h/stats/info/?109';
							footerText = 'Complete Money Winners';
							break;
						default:
						break;
					}
					
					$$('#'+theHTMLID+' .tourStandingsContentRightFullLBLink')[0].innerHTML = '<a href="'+footerLink+'" class="tourStandingsLink">'+footerText+'</a>';
					$$('#'+theHTMLID+' .tourStandingsTableContainer')[0].innerHTML = getMoneyTable(thisObj.tID, thisObj.rendererID);
				}
			}
		}
		$(theHTMLID).innerHTML += '<!-- tID:'+thisObj.tID+' '+tour+'Ts['+i+'] -->';
	}

}

function getMoneyTable (tID, rendID) {
	thePoints = false;
	var tour = tID.substring(0,1).toLowerCase();
	var output = '<table class="tourStandingsNonLive tourStandingsColors_'+tour+'"><tr class="logo"><td colspan="4"><img src="http://i.cdn.turner.com/pgatour/.element/img/5.0/sect/'+tour+'/standingsLogo.gif" /></td></tr>'
	output += '<tr class="topRow"><td class="rank">RANK</td><td class="name">PLAYER</td><td class="evts">EVENTS</td><td class="pts">';
	if (theCurrentTour == 'r' && rendID.match(theCurrentTour.toUpperCase())) {
		output += 'POINTS';
	} else {
		output += 'POINTS';
	}
	
	output += '</td></tr>';

	// Grab the JSON and assign it to theScore
	if (tour=='r' || tour=='h' || tour=='s') {
		var grabFile = '/15s/.element/ssi/auto/3.0/sdms/data/stats/'+tour+'/'+taD.getFullYear()+'/standing.json';
	} else {
		var grabFile = '/15s/.element/ssi/auto/3.0/sdms/data/stats/'+tour+'/2009/standing.json';
	}
	//new Ajax.Request('/.element/ssi/auto/3.0/sdms/data/stats/'+tour+'/2009/standing.json', {
	new Ajax.Request(grabFile, {
		method: 'get',
		asynchronous: false,
		onSuccess: function(transport) { thePoints = transport.responseText.evalJSON(true); }
	});
	if (thePoints) {
		pCnt = thePoints.hpstanding.standings.player.length;
		for (var i=0; i<pCnt; i++) {
			var thisPlayer = thePoints.hpstanding.standings.player[i];
			thisClass = ((i+1)%2)? 'odd':'even';
			lastClass = ((i+1)==pCnt)? ' tourStandingsBotRowBorder':'';
			output += '<tr class="'+thisClass+lastClass+'"><td class="rank">'+thisPlayer.rank+'</td><td class="name">'+thisPlayer.name+'</td><td class="evts">'+thisPlayer.events+'</td><td class="pts">'+thisPlayer.points+'</td></tr>';
		}
		output += "</table>";
		thePoints = ''; // Clear the points!
		return output;
	}

	output += '</table>'

	return ''; // return nothing
}

function getLBTable (tID) {
	if (typeof myTop5Holder[tID] == 'undefined') {
		myTop5Holder[tID] = timestamp();
	}
	var output = '<table class="tourStandingsLive"><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>';
	var theScore = {};

	// Grab the JSON and assign it to theScore
	new Ajax.Request('/15s/.element/ssi/auto/3.0/sdms/data/leaderboards/'+tID+'/'+taD.getFullYear()+'/top5LB.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 += '<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>';
		}
		output += "</table>";
		myTop5Holder[tID] = theScore.leaderboard.cts;
		return output;
	}
}

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;
}

// Grab and store the TV times per tour, but only AJAX them from them if we don't already have them
function doStandingsTimes(tour) {
	tour = tour.toLowerCase();

	if (myTVTimesHolder.get(tour) == false) {
		if(useObj = eval(tour+'Ts')) {

			sp_debugger += 'Using the '+tour+'Ts cms object!\n';

			useObj.each(function(cmsObj) {
				var theHTMLID = 'tourStandings_'+cmsObj.rendererID;
				sp_debugger += 'Looking for '+theHTMLID+' for tournament '+cmsObj.tID+'\n';
				if ($(theHTMLID)) {
					var tvTimes = '';
					if(tvTimes = getBroadcastTimes(cmsObj.tID)) {

						// Now for the tv & XM schedules.
						if (tvTimes.nextTV) {
							// Are there TV Times?
							if (tvTimes.tv_times[tvTimes.nextTV].tv) {
								$$('#'+theHTMLID+' .tourTVTimesDate')[0].innerHTML = days[tvTimes.day]+', '+
																					 months[parseInt((tvTimes.month*1))]+' '+
																					 tvTimes.month_day;
								var tempOut = '';

								tvLen = tvTimes.tv_times[tvTimes.nextTV].tv.length;
								tvTimes.tv_times[tvTimes.nextTV].tv.each(function(thisTime,i) {
									var ico = networkIcons[thisTime.network.toLowerCase()];
									var sTime = thisTime.standardSTime;
									var eTime = thisTime.standardETime;
									// If time is o'clock, drop the zeros
									//if (sTime.split(':')[1]=='00'){sTime = sTime.split(':')[0]}
									//if (eTime.split(':')[1]=='00'){eTime = eTime.split(':')[0]}
									// If A/P.M is the same, only add it to the eTime.
									if (thisTime.standardETimeAPM == thisTime.standardSTimeAPM){
										eTime += thisTime.standardETimeAPM;
									} else {
										sTime += thisTime.standardSTimeAPM;
										eTime += thisTime.standardETimeAPM;
									}

									var optClass = (tvLen<=2)? ' class="tourTVTimesSingleRowItem"' : '';
									tempOut += '<li' + optClass + '><img src="http://i.cdn.turner.com/pgatour/.element/img/5.0/global/channels/'+ico+'"> '+sTime+'-'+eTime+'</li>';
								});
								$$('#'+theHTMLID+' .tourTVTimesChannels')[0].innerHTML = "<ul>"+tempOut+"</ul>";
								$$('#'+theHTMLID+' .tourStandingsTVTimes')[0].removeClassName('hide');
							}// if (tvTimes.tv_times[tvTimes.nextTV].tv)
						}// (tvTimes.nextTV)
						// Are there XM Times?
						if (tvTimes.xm_times && tvTimes.xm_times.length > 0) {
							
							var tempOut = '';
							tvTimes.xm_times.each(function(thisXMTime){
								var thisDay = days[thisXMTime.day];
								var sTime = thisXMTime.standardSTime;
								var eTime = thisXMTime.standardETime;
								// If time is o'clock, drop the zeros
								if (sTime.split(':')[1]=='00'){sTime = sTime.split(':')[0]}
								if (eTime.split(':')[1]=='00'){eTime = eTime.split(':')[0]}

								// If A/P.M is the same, only add it to the eTime.
								if (thisXMTime.standardETimeAPM == thisXMTime.standardSTimeAPM){
									eTime += thisXMTime.standardETimeAPM;
								} else {
									sTime += thisXMTime.standardSTimeAPM;
									eTime += thisXMTime.standardETimeAPM;
								}

								tempOut += '<li>'+thisDay+': '+sTime+'-'+eTime+'</li>';
							});
							$$('#'+theHTMLID+' .tourXMTimes')[0].innerHTML = '<ul>'+tempOut+'</ul><a href="javascript:void(window.open(\'/multimedia/xmplayer/index.html\',\'xmplayer\',\'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=705,height=510\'));" class="tourStandingsLink">Listen NOW!</a>';
							$$('#'+theHTMLID+' .tourStandingsXMTimes')[0].removeClassName('hide');
						} // if (tvTimes.xm_times)
						else { sp_debugger += 'No XM Times for '+cmsObj.tID+'\n'; }

					} else { sp_debugger += 'Failed to get TV Times for '+cmsObj.tID+'\n'; }
				} else { sp_debugger += 'Failed to find element '+theHTMLID+' for tournament '+cmsObj.tID+'\n'; }
			});
			myTVTimesHolder.set(tour,'true');
		} else { sp_debugger += ''+tour+'Ts evaled to false!\n'; }
	} else { sp_debugger += 'Already got times for '+tour+'\n'; }
}


// Next top5 Holder
myTop5Holder = new Array();
myTVTimesHolder = $H({r:false,s:false,h:false});