/*

Clean up functions moved to /www/pgatour/.element/js/5.0/global/lib.js

*/

	function getRendererID(_tourObj) {
		var tourCode = _tourObj.code;
		var tourID = _tourObj.tID;
		var usableObj = null;
		var debugMsg = '';
		var theRendID = '';

		switch(_tourObj.code) {
			case 'r' :
				debugMsg += 'using rTs\n';
				usableObj = rTs;
				break;
			case 's' :
				debugMsg += 'using sTs\n';
				usableObj = sTs;
				break;
			case 'h' :
				debugMsg += 'using hTs\n';
				usableObj = hTs;
				break;
			default :
				usableObj = null;
				break;
		}


		if (usableObj != null) {
			for (var i=0, uoLen = usableObj.length; i<uoLen; i++) {
				debugMsg += 'rendererID = '+usableObj[i].rendererID+'\n';
				debugMsg += 'Straight from rTs '+rTs[i].rendererID;
				//alert(debugMsg);
				if (usableObj[i].tID == tourID) {
					theRendID = usableObj[i].rendererID;
					return theRendID;
				}
			}
		}

		return null;
	}

	function loadStandingsContent() {
		var months = ["", "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept", "Oct","Nov","Dec"];
		var days = {"MON":"Mon","TUE":"Tue","WED":"Wed","THU":"Thu","FRI":"Fri","SAT":"Sat","SUN":"Sun"};
		var networkIcons = {"golf":"golf_channel.gif","cbs":"cbs.gif","nbc":"nbc.gif","tnt":"tnt.gif"};

		//var theCs = ['r'];
		var theCs = ['r','s','h'];
		if (theCs){
			for (var i=0, cLen=theCs.length; i<cLen; i++) {
				if (undefined != mTimes[theCs[i]].tour){
					for (var j=0, tLen=mTimes[theCs[i]].tour.length; j<tLen; j++) {
						var theC = mTimes[theCs[i]].tour[j];
						if (theC){
						   var theHTMLID = 'tourStandings_' + (getRendererID(theC) || 'E'); //theC.tID;

							// Adjust the Title
							//$$('#'+theHTMLID+' .tourStandingsTitle')[0].innerHTML = theC.name;

							// Now for the tv & XM schedules.
							if (theC.nextTV) {

								// Are there TV Times?
								if (theC.tv_times[theC.nextTV].tv){
									$$('#'+theHTMLID+' .tourTVTimesDate')[0].innerHTML = days[theC.day]+', '+months[parseInt(theC.month)]+' '+theC.month_day;
									var tempOut = '';
									for (var k=0, tvLen=theC.tv_times[theC.nextTV].tv.length; k<tvLen ; k++) {
										var thisTVTime = theC.tv_times[theC.nextTV].tv[k];
										var ico = networkIcons[thisTVTime.network.toLowerCase()];
										var sTime = thisTVTime.standardSTime;
										var eTime = thisTVTime.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 (thisTVTime.standardETimeAPM == thisTVTime.standardSTimeAPM){
											eTime += thisTVTime.standardETimeAPM;
										} else {
											sTime += thisTVTime.standardSTimeAPM;
											eTime += thisTVTime.standardETimeAPM;
										}


										var optClass = (tvLen==2)? ' class="tourTVTimesSingleRowItem"' : '';
										tempOut += '<li' + optClass + '><img src="/.element/img/5.0/global/channels/'+ico+'"> '+sTime+'-'+eTime+'</li>';
									} // k for loop
									$$('#'+theHTMLID+' .tourTVTimesChannels')[0].innerHTML = "<ul>"+tempOut+"</ul>";
									$$('#'+theHTMLID+' .tourStandingsTVTimes')[0].removeClassName('hide');
								}// if (theC.tv_times[theC.nextTV].tv)
							}// (theC.nextTV)

							// Are there XM Times?
							if (theC.xm_times) {
								var tempOut = '';
								for (var k=0, xmLen=theC.xm_times.length; k<xmLen ; k++) {
									var thisXMTime = theC.xm_times[k];
									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>';
								} // k for loop
								$$('#'+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 (theC.xm_times)

							// Kill theC to be safe.
							theC = null;
						}// if (theC)

					}// j For Loop

				} // if (undefined != mTimes[theCs[i]].tour)

			}// i For Loop

		}// if (theCs)
	}

	function switchStandingsTab(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="' + 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) {
		var pbAdDone = 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);
				}

				if (thisObj.rendererID.match(theCurrentTour.toUpperCase()) && pbAdDone == false && thisObj.isLive == true) {
					pbAdDone = true;
					$$('#'+theHTMLID+' .tourPoweredByIF')[0].src = '/.element/ssi/sect/5.0/'+theCurrentTour+'/91x20_ad.html';
				}
				
			} 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/?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);
					}
				}
			}
		}

	}

	function getMoneyTable (tID, rendID) {
		var tour = tID.substring(0,1).toLowerCase();
		var output = '<table class="tourStandingsNonLive tourStandingsColors_'+tour+'"><tr class="logo"><td colspan="4"><img src="/.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.hpstanding) {
			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 output;
	}

	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;
	}
// Next top5 Holder
myTop5Holder = new Array();