var defaultRound = 4;

var xmlhttp = null;
/*var dataPath = "../xml/display.1618.xsl";*/
var dataPath = "../syndteetimes.xml";

function setupXMLHTTP(path,changeHandler) {
	if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
	else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	if(xmlhttp) {
		xmlhttp.onreadystatechange = eval(changeHandler);
		xmlhttp.open("GET", path, true);
		xmlhttp.send(null);
	}
}
function xmlError(e) { /* there was an error, show the user */ alert(e); } /* end function xmlError */

function getNumEntries(xml,tag) { return (xml.split(tag).length)-1; }

var roundNum = location.hash !== "" ? parseInt(location.hash.replace('#round',''),10) : defaultRound;
roundNum = roundNum > 4 ? defaultRound : roundNum; //prevent overage on round # requests
var maxSegments = null;
var maxGroups = null;
var maxPlayersPerGroup = null;
var maxRounds = 0;
function displayPTTXML(xmlData) {
	var xml = xmlData;
	var XMLObj = new XMLDoc(xml, xmlError);
	
	var pttTable = $('ptt_table');
	var rowClass = null, nextTBody = null, nextRow = null, nextCell = null, nextCellData = null;
	
	for (r=1; r<5; r++) { //loop rounds
		if (XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[0]')) {
			maxPlayersPerGroup = XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]').getAttribute("MaxPlayersPerGroup");
			//alert("r" + r + " maxPlayersPerGroup: " + maxPlayersPerGroup);
			maxSegments = getNumEntries(XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]').getUnderlyingXMLText(),"<Segment ");
			//alert("r" + r + " maxSegments: " + maxSegments);
			
			nextTBody = document.createElement('tbody');
			nextTBody.id = "pttTBody" + r;
//			if (r !== roundNum) nextTBody.className = "hide";
			if (r !== roundNum) {
				nextTBody.className = "hideTBody";
			} else {
				nextTBody.className = "showTBody";
			}
			for (s=1; s<maxSegments+1; s++) { //loop segments
				rowClass = "even";
				maxGroups = getNumEntries(XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]').getUnderlyingXMLText(),"<Group ");
				//alert("r" + r + " s" + s + " maxGroups: " + maxGroups);
				
				if (s == 1 || s == 3) {
					nextTBodyTR = document.createElement('tr');
				}
				nextTBodyTRTD = document.createElement('td');
				nextTBodyTRTDTable = document.createElement('table');
				nextTBodyTRTDTable.cellSpacing = '0';
				nextTBodyTRTDTable.cellPadding = '0';
				nextTBodyTRTDTable.border = '0';
				nextTBodyTRTDTableTbody = document.createElement('tbody');
				
				//Blank TD
				nextTBodyTRTDTableTR = document.createElement('tr');
				nextTBodyTRTDTableTRTD = document.createElement('td');
				nextTBodyTRTDTableTRTD.className = "even";
				nextCellData = document.createTextNode("\u00a0");
				nextTBodyTRTDTableTRTD.appendChild(nextCellData);
				nextTBodyTRTDTableTR.appendChild(nextTBodyTRTDTableTRTD);
				nextTBodyTRTDTableTbody.appendChild(nextTBodyTRTDTableTR);
				nextTBodyTRTDTable.appendChild(nextTBodyTRTDTableTbody);
				
				//Group Tee # TH
				nextTBodyTRTDTableTR = document.createElement('tr');
				nextTBodyTRTDTableTRTD = document.createElement('td');
				nextTBodyTRTDTableTRTD.className = "odd";
				nextCellData = document.createTextNode("Tee " + XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]').getAttribute("StartTee"));
				nextTBodyTRTDTableTRTD.appendChild(nextCellData);
				nextTBodyTRTDTableTR.appendChild(nextTBodyTRTDTableTRTD);
				nextTBodyTRTDTableTbody.appendChild(nextTBodyTRTDTableTR);
				nextTBodyTRTDTable.appendChild(nextTBodyTRTDTableTbody);

				//for (g=0; g<maxGroups; g++) { //loop groups
				// reverse the groups of players so they are in order of tee time
				for (g=maxGroups-1; g>=0; g--) { //loop groups
					//alert("GroupID: " + XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']').getAttribute("GroupID"));
					nextTBodyTRTDTableTR = document.createElement('tr');
					nextTBodyTRTDTableTRTD = document.createElement('td');
					nextTBodyTRTDTableTRTD.className = rowClass;
					nextCellData = XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']').getAttribute("StartTime");
					nextCellData += ' - ';
					nextCellData = document.createTextNode(nextCellData);
					nextTBodyTRTDTableTRTD.appendChild(nextCellData);
					
					var playersPerGroup = XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']').getElements().length; //.children.length;

					for (p=0; p<playersPerGroup; p++) { //loop players
						//alert("Player: " + XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']/Player['+p+']').getAttribute("FLName"));
						nextCellData = document.createElement('a');
						playerID = "0" + XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']/Player['+p+']').getAttribute("TournamentPlayerID");
						playerID1 = playerID.substring(0,2);
						playerID2 = playerID.substring(2,4);
						playerID3 = playerID.substring(4,6);
						nextCellData.href = "http://www.pgatour.com/players/" + playerID1 + "/" + playerID2 + "/" + playerID3 + "/";
						nextCellData.onclick= function() { return popWinCust(this.href,'pop','no','no','no','no','no','yes','yes',1024,768,0,0);};
						nextCellData.innerHTML = XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']/Player['+p+']').getAttribute("FLName").replace("&apos;","'");
						//nextCellDataText = document.createTextNode(XMLObj.selectNode('/Round[@RoundNumber="'+r+'"]/Course[0]/Segment[@SegmentID="'+s+'"]/Group['+g+']/Player['+p+']').getAttribute("FLName"));
						//nextCellData.appendChild(nextCellDataText);
						nextTBodyTRTDTableTRTD.appendChild(nextCellData);

						if (p < (playersPerGroup-1)) {
							nextCellData = document.createTextNode(", ");
							nextTBodyTRTDTableTRTD.appendChild(nextCellData);
						}
						
					} //loop players
					
					nextTBodyTRTDTableTR.appendChild(nextTBodyTRTDTableTRTD);
					nextTBodyTRTDTableTbody.appendChild(nextTBodyTRTDTableTR);
					nextTBodyTRTDTable.appendChild(nextTBodyTRTDTableTbody);
					
					rowClass = rowClass == "odd" ? "even" : "odd";
					
				} //loop groups
				
				nextTBodyTRTD.appendChild(nextTBodyTRTDTable);
				nextTBodyTR.appendChild(nextTBodyTRTD);
				if (s == 2 || s == 4) { nextTBody.appendChild(nextTBodyTR); }
				if(maxSegments == 1) {
					nextTBody.appendChild(nextTBodyTR);
					nextTBodyTRTDTable.className = "singleColumn";
				}
			} //loop segments
		
		pttTable.insertBefore(nextTBody,getChildElementsByType('tfoot',pttTable)[0]);
		maxRounds++;
		
		} else {
			//alert("r" + r + " contains no segments");
//			nextTBody = document.createElement('tbody');
//			nextTBodyTR = document.createElement('tr');
//			nextTBodyTRTD = document.createElement('td');
//			nextTBodyTRTDTable = document.createElement('table');
//			nextTBodyTRTDTableTbody = document.createElement('tbody');
//			nextTBodyTRTDTableTbodyTR = document.createElement('tr');
//			nextTBodyTRTDTableTbodyTRTD = document.createElement('td');
//			text = document.createTextNode("test")
//			nextTBodyTRTDTableTbodyTRTD.appendChild(text);
//			nextTBodyTRTDTableTbodyTR.appendChild(nextTBodyTRTDTableTbodyTRTD);
//			nextTBodyTRTDTableTbody.appendChild(nextTBodyTRTDTableTbodyTR);
//			nextTBodyTRTDTable.appendChild(nextTBodyTRTDTableTbody);
//			nextTBodyTRTD.appendChild(nextTBodyTRTDTable);
//			nextTBodyTR.appendChild(nextTBodyTRTD);
//			nextTBody.appendChild(nextTBodyTR);
//			pttTable.insertBefore(nextTBody,getChildElementsByType('tfoot',pttTable)[0]);
		}
	} //loop rounds
	
	writePagination(roundNum);
	
	pttTable.removeChild(getChildElementsByType('tbody',pttTable)[0]);
	
	getElementsByClassName('timestamp', 'span', $('ptt_table_lastrow'))[0].innerHTML = "Information Updated: " + XMLObj.docNode.getAttribute("CurrentTime");
}

function writePagination(currPage) {
	var pagesDiv = $('pagination');
	currPage = parseInt(currPage,10);
	pagesDiv.innerHTML = "Round";
	for (p=1; p<5; p++) {
		if (p == currPage) {
			pagesDiv.innerHTML += '&nbsp;'+p;
		} else if ( p > maxRounds) {
			pagesDiv.innerHTML += '';
		} else {
			pagesDiv.innerHTML += '&nbsp;<a href="#round'+p+'" onclick="navigatePage('+p+',location.hash)">'+p+'</a>';
		}
	}
}

function navigatePage(destPage,currPage) {
	currPage = currPage !== "" ? parseInt(currPage.replace('#round',''),10) : 1;
	if ($('pttTBody'+currPage)) { $('pttTBody'+currPage).className = 'hideTBody'; }
	$('pttTBody'+destPage).className = 'showTBody';
	writePagination(destPage);
}

function processData() {
	if(xmlhttp.readyState == 4) {
		if(xmlhttp.status == 200) {
			displayPTTXML(xmlhttp.responseText);


			if (document.getElementById("pagination"))
			{
			    //alert(document.getElementById("pagination").innerHTML.indexOf("Round") );
			    if ((document.getElementById("pagination").innerHTML.indexOf("Round") > -1) && (document.getElementById("pagination").innerHTML.indexOf("4") > -1 ))
			        document.getElementById("pagination").innerHTML ="Round 4";
            }

		} else { /* updateStatus(invalidText); */ }
	}
}
function loadData() {
	setupXMLHTTP(dataPath,"processData");
	
	
	return false;
}
WindowOnload(function() { loadData(); });
