/**
 * Leaderboard scripts
 *
 * @Henry Postulart
 * @1.0
 */

var temp = null;
var temp2 = null;
var oH = new Array();
var tournFolder = "";
var reqPID = null;
var hideLeader = false;
var scorecardData;

function initTopTenLeaderBoard(folder) {
	var t = queryString("TID");
        if (t != "false") tournCode = t.toLowerCase();
        var f = queryString("folder") ;
        if (f != "false") tournFolder = f.toLowerCase();
        if (tournFolder || typeof folder != typeof undefined) {
                if (typeof PID == typeof undefined) {
                        var p = queryString("PID");
                        if (p != "false") reqPID = p.toLowerCase();
                } else {
                        reqPID = PID;
                        hideLeader = true;
                }
                // no test for !tournFolder this may be called more than once
                // and the new folder must be used
                if (typeof folder != typeof undefined)  tournFolder = folder;
                var reader = new leaderReader(tournFolder, "leaderboard_top10.xml");
                temp = window.setInterval ( function() { waitForTopTenXML(reader, tournFolder); }, 100);
        } else if (tournCode) {
                var reader = new leaderReader("current_" + tournCode, "leaderboard_top10.xml");
                temp = window.setInterval ( function() { waitForTopTenXML(reader, currentTourney); }, 100);
        }
}
function waitForTopTenXML(reader, folder) {
	if (reader.xml) {
		window.clearInterval(temp)
		widget = new toptenLeaderWidget(reader, folder);
	}
}
function initHomeLeaderBoard(count) {
	var div = $("lboard-body");
	if (div && tournCode) {
		var reader = new leaderReader("current_" + tournCode, "leaderboard_top10.xml");
		temp = window.setInterval ( function() { waitForHomeXML(div, reader, count); }, 100);
	}
}

function findFullLeaderBoard(folder, PID) {
	var t = queryString("TID");
	if (t != "false") tournCode = t.toLowerCase();
	var f = queryString("folder") ;
	if (f != "false") tournFolder = f.toLowerCase();
	if (tournFolder || typeof folder != typeof undefined) {
		if (typeof PID == typeof undefined) {
			var p = queryString("PID");
			if (p != "false") reqPID = p.toLowerCase();
		} else {
			reqPID = PID;
			hideLeader = true;
		}

		// no test for !tournFolder this may be called more than once
		// and the new folder must be used
		if (typeof folder != typeof undefined)  tournFolder = folder;
		var reader = new leaderReader(tournFolder, "ModifiedLeaderboard.xml");
		temp = window.setInterval ( function() { waitForFullXML(reader, tournFolder); }, 100);
	} else if (tournCode) {
		var reader = new leaderReader("current_" + tournCode, "ModifiedLeaderboard.xml");
		temp = window.setInterval ( function() { waitForXML(reader, currentTourney); }, 100);
	}
}

function initFullLeaderBoard(folder) {
	if (folder) {
		try {
			var reader = new leaderReader(folder, "ModifiedLeaderboard.xml");
			temp = window.setInterval ( function() { waitForFullXML(reader, folder); }, 100);
		} catch(e) {
			var s  = "e is: " + e + "\n";
			    s += "e.number is: " + (e.number & 0xFFFF) + "\n";
			    s += "e.description is: " + e.description + "\n";
			    s += "e.name is: " + e.name + "\n";
			    s += "e.message is: " + e.message;
			alert(s);
		}
	}
}

function waitForHomeXML(div, reader, rows) {
	if (reader.xml) {
		window.clearInterval(temp)
		var widget = new leaderWidget(div, reader, rows);
	} 
}

function waitForFullXML(reader, folder) {
	if (reader.xml) {
		window.clearInterval(temp)
		widget = new fullLeaderWidget(reader, folder);
	}
}

function waitForXML(reader, handler) {
	if (reader.xml) {
		window.clearInterval(temp);
		oH[oH.length] = new handler(reader);
	}
}

if (typeof Class != "undefined") {
	var currentTourney = Class.create();
	currentTourney.prototype = {
		initialize : function(reader) {
			this.xml = reader.xml;
			this.text = reader.text;
			this.tourn = this.xml.getElementsByTagName("Tourn")[0];
			this.tournCode = this.tourn.getAttribute("TourCode");
			this.tournID = this.tourn.getAttribute("TournId");
			this.time = this.tourn.getAttribute("CurTime");
			this.year = this.time.substr(this.time.lastIndexOf("/") + 1);
			if (this.tournCode.toLowerCase() == tournCode.toLowerCase()) {
				tournFolder =  (tournCode + this.year + this.tournID);
				initFullLeaderBoard(tournFolder);
			}
		}
	}
}

if (typeof Class != "undefined") {
	var leaderReader = Class.create();
	leaderReader.prototype = {

		xml      : null,
		text     : null,
		rootPath : "/golf/static/xml/leaderboard",
		src      : "",
		hideError : false,
		failed    : false,

		initialize : function(tFolder, file, bHideError) {
			try {
				if (this.initialize.arguments.length == 3) {
					this.hideError = bHideError;
				}
				this.src = this.rootPath + "/" +  tFolder + "/" + file;
				this.src = this.src.replace(/\/\//, "/");
				this.getData(this.src);
			} catch(e) {/* discard error(s) */}

		},

		getData: function (url) {
			if (url) {
				this.xmlHTTP = new Ajax.Request(url, {asynchronous: true, onSuccess: (this.handlerFunc).bindAsEventListener(this), onFailure: (this.errFunc).bindAsEventListener(this), method: "get"  });
			}
		},

		handlerFunc: function(t) {
			this.xml  = t.responseXML;
			this.text = t.responseText;
		},

		errFunc: function(t) {
			this.failed = true;
			if (!this.hideError) {
				alert(global404ErrorMessage);
			}
		}
	};

	var leaderWidget = Class.create();
	leaderWidget.prototype = {

		handle1 : null,
		handle2 : null,
		interval : 5 * 60 * 1000,
		testReader : null,

		initialize : function(div, reader, numRows) {
			try {
				this.div = div;
				this.reader = reader;
				this.numRows = numRows;
				this.eventHeading = div.getElementsByTagName("h2")[0];
				this.roundHeading = div.getElementsByTagName("h4")[0];
				this.table = div.getElementsByTagName("table")[0];
				this.tbody = this.table.getElementsByTagName("tbody")[0];
				this.xml  = reader.xml;
				this.text = reader.text;
				this.tourn = this.xml.getElementsByTagName("Tourn")[0];
				this.eventHeading.innerHTML = this.tourn.getAttribute("Name");

				/* TO-DO: Determine data that identifies when tournament is over, so heading can reflect that state */
				this.roundHeading.innerHTML = "Round " + this.tourn.getAttribute("CurRnd") + " Scoring";

				this.players = $A(this.xml.getElementsByTagName("Player"));
				var count = 0;
				this.players.each( function(p) {
					if (count < numRows) {
						var odd = (count % 2 == 0);
						var row = this.buildRow(p, odd);
						this.tbody.appendChild(row);
						count++;
					} else { throw $break; }
				}.bind(this));
				//this.link = document.getElementsByClassName("lboard-footer", this.div)[0].getElementsByTagName("a")[0];
				//this.link.href = "/golf/tours_news/leaderboard/0,28360," + tournCode + ",00.html?TID=" + tournCode;

				this.handle = window.setInterval(function() {this.test();}.bind(this), this.interval);
			} catch(e) {/* discard error(s) */}
		},

		test : function() {
			this.testReader = new leaderReader("current_" + tournCode, "leaderboard_top10.xml", this.numRows);
			this.handle2 = window.setInterval(function() {this.update();}.bind(this), 250);
		},

		update : function() {
			if (this.testReader.text && this.testReader.text != this.text) {
				window.clearInterval(this.handle2)
				this.tbody.innerHTML = "";
				this.initialize(this.div, this.testReader, this.numRows);
			}
		},

		buildRow : function(player, odd)  {
			var count = 0;
			var c = (odd) ? "odd" : "even";
			var row = this.buildElem("tr", c);
			var td  = this.buildElem("td");
			td.appendChild(document.createTextNode(player.getAttribute("CurPos")));
			row.appendChild(td);
			td  = this.buildElem("td", "player");
                        td.appendChild(document.createTextNode(player.getAttribute("FInit") + ". " + player.getAttribute("Lname")));
                        row.appendChild(td);
			if (player.getAttribute("Thru") == "") {
				td  = this.buildElem("td");
				td.colSpan = 2;
				var ttime = player.getAttribute("TTimeEST");
				if(ttime.indexOf(':') == -1) {
				  var hour = Number(ttime.substring(0, 2));
				  var minute = Number(ttime.substring(2));
				  var amOrPm = 'am';
				  if(hour >= 12) {
					  amOrPm = 'pm';
					  if(hour > 12) {
						  hour = hour - 12;
					  }
				  }
				  if(minute < 10) { minute = '0' + minute; }
				  ttime = hour + ':' + minute + ' ' + amOrPm;
				}
				td.appendChild(document.createTextNode(ttime));
				row.appendChild(td);
			} else {
				td  = this.buildElem("td");
				td.appendChild(document.createTextNode(player.getAttribute("CurParRel")));
				row.appendChild(td);
				td  = this.buildElem("td");
				td.appendChild(document.createTextNode(player.getAttribute("Thru")));
				row.appendChild(td);
			}
			td  = this.buildElem("td", "total");
			td.appendChild(document.createTextNode(player.getAttribute("TournParRel")));
			row.appendChild(td);
			return row;
		},

/* Utility functions */
		buildElem : function(type, className) {
			var el = document.createElement(type);
			if (className) el.className = className;
			return el;
		},

		nodeContent : function(node) {
			return node.firstChild.nodeValue;
		}
	};

	var fullLeaderWidget = Class.create();
	fullLeaderWidget.prototype = {

		handle1    : null,
		handle2    : null,
		interval   : 2 * 60 * 1000,
		testReader : null,
		xml        : null,
		text       : null,
		folder     : "",
		nbsp       : "&#160;",

		headerRegion  : null,
		hTourName     : null,
		atourInfo     : null,
		tCommon       : null,
		commonSortBy  : "SortIndex",
		tCustom       : null,
		customSortBy  : "SortIndex",
		sortDir       : {asc: "asc", desc: "desc"},
		imgFlagPath   : "http://img.timeinc.net/golf/static/img/leaderboard/flags/",
		imgPlayerPath : "http://img.timeinc.net/golf/static/img/stats/players/",
		activeRow     : null,

		tourNode      : null,
		tourName      : "",
		players       : null,
		customPlayers : null,
		numRounds     : 0,
		tournID       : "",
		scoreCards    : [],
		scoreStats    : [],
		courseName    : [],

		customCookieName      : "",
		customCookieValue     : "",
		customCookieDays      : 10,
		customSortCookieName  : "",
		customSortCookieValue : "",
		commonSortCookieName  : "",
		commonSortCookieValue : "",
		analyzerDefaultCount  : 3,

		scoreCard : { Eagles: ["Eagles", "eagle", -2],
		              Birdies: ["Birdies", "birdie", -1],
		              Par: ["Par", "", 0],
		              Bogeys: ["Bogeys", "bogey", 1],
		              DoubleBogeys: ["Double Bogeys/+", "double-bogey", 2]
		},

		initialize : function(reader, folder) {
			try {
				/* define required page elements */
				this.headerRegion = document.getElementsByClassName("lboard-header")[0];
				this.container = $("lboard-container");
				this.hTourName = this.headerRegion.getElementsByTagName("h2")[0];
				this.atourInfo = $A(this.headerRegion.getElementsByTagName("li"));
				try {
					this.tCustom = document.getElementsByClassName("lboard-custom")[0].getElementsByTagName("table")[0];
				} catch(e) { /* discard error(s) */ }
				if (this.tCustom) {
					this.tCustom.setAttribute("SortBy", this.customSortBy);
					this.tCustom.setAttribute("SortDir", this.sortDir.asc);
				}
				this.tCommon = document.getElementsByClassName("lboard-all")[0].getElementsByTagName("table")[0];
				this.tCommon.setAttribute("SortBy", this.commonSortBy);
				this.tCommon.setAttribute("SortDir", this.sortDir.asc);

				// values are left over from prevous object. these need to
				// be initialized
			    	this.scoreCards = [];
			    	this.scoreStats = [];
			    	this.courseName =[];
			    	this.tournID = "";
			    	this.tourNode = null;
			    	this.tourName = null;

				/* capture required data elements */
				this.xml = reader.xml;
				this.text = reader.text;
				this.folder = folder;
				this.players = $A(this.xml.getElementsByTagName("Player"));
				this.drawHeading();
				this.drawTable(this.tCommon);
				if (document.getElementById("content").className.indexOf("tours-analyzer") >= 0) {
					if (this.customCookieValue == "") {
						var s = ""
						this.players.each( function (p, i) {
							if ( i == 3 ) throw $break;
							var pid = p.getAttribute("PID");
							if ( i < 2 ) s += pid + ",";
							else  s += pid;
						}.bind(this));
						this.createCookie(this.customCookieName, s, this.customCookieDays);
						this.customCookieValue = this.readCookie(this.customCookieName);
					}
				}
				if (this.tCustom) {
					this.drawTable(this.tCustom);
				}
				// BL - if the user is viewing the tour analyzer page, make this functionality available
				if (document.getElementById("content").className.indexOf("tours-analyzer") >= 0) {
					placeAnalyzer(this.customCookieValue, this.numRounds);
				}
				if (this.activeRow) this.activeRow.scrollIntoView(true);
				this.handle = window.setInterval(function() {this.test();}.bind(this), this.interval);
			} catch(e) {/* discard error(s) */}
		},

		drawHeading : function() {
			this.tourNode = this.xml.getElementsByTagName("Tourn")[0];
			this.tournId = this.tourNode.getAttribute("TournId");
			this.tourName = this.tourNode.getAttribute("Name");
			this.customCookieName = "myPlayers_" + this.tournID;
			this.customCookieValue = this.readCookie(this.customCookieName);
			this.hTourName.innerHTML = this.tourNode.getAttribute("Name");
			var loc = this.tourNode.getAttribute("Loc");
			loc += (this.tourNode.getAttribute("localCity")) ? ", " + (this.tourNode.getAttribute("localCity")) : "";
			loc += (this.tourNode.getAttribute("LocState")) ? ", " + (this.tourNode.getAttribute("LocState")) : "";
			var links = this.atourInfo[0].getElementsByTagName("span");
			if (links && links.length) {
                        	links[0].innerHTML = loc;
                        	for (var i = 1; i < links.length; i++) {
                                	this.atourInfo[0].removeChild(this.atourInfo[0].getElementsByTagName("a")[1]);
                        	}
			}
			this.courses = $A(this.xml.getElementsByTagName("Course"));
			this.atourInfo[1].getElementsByTagName("span")[0].innerHTML = this.tourNode.getAttribute("TournStartDate");
			this.atourInfo[2].getElementsByTagName("span")[0].innerHTML = this.tourNode.getAttribute("Purse");
			this.numRounds = this.tourNode.getAttribute("NumRnds");
			this.numCourses = this.courses.length;
			this.currRound = this.tourNode.getAttribute("CurRnd").substr(0,1);
		},

		drawTable : function(tbl) {
			/* Only draw table header if required */
			if (!hideLeader) {
				var thead = $A(tbl.getElementsByTagName("thead"))[0];
				if (!tbl.getAttribute("headerEvents")) {
					var hLinks = $A(thead.getElementsByTagName("a"));
					hLinks.each( function(a) {
						a.setAttribute("sortDir", this.sortDir.asc);
						Event.observe(a, "click", (function(e) {
							var el = Event.findElement(e, "a");
							var attr = el.href.substr(el.href.lastIndexOf("/") + 1);
							var tb = Event.findElement(e, "table");
							tb.setAttribute("SortBy", attr);
							var sd = el.getAttribute("SortDir");
							tb.setAttribute("SortDir", sd);
							this.drawTable(tb)
							sd = (sd==this.sortDir.asc) ? this.sortDir.desc : this.sortDir.asc;
							el.setAttribute("sortDir", sd);
							Event.stop(e);
						}).bindAsEventListener(this))
					}.bind(this) );
					var roundRow = document.getElementsByClassName("sub", thead)[0];
					for (var i = 0; i < this.numRounds; i++) {
						var th = this.buildElem("th")
						//var a = this.buildElem("a");
						var rnd = parseInt(i + 1);
						//a.href = "Rnd_Num_" + rnd;
						//a.innerHTML = rnd;
						//th.appendChild(a);
						th.appendChild(document.createTextNode(rnd));
						roundRow.appendChild(th);
					}
					tbl.setAttribute("headerEvents", "true");
				}
			}

			var tbody = $A(tbl.getElementsByTagName("tbody"))[0];
			while(tbody.childNodes.length) {
				tbody.removeChild(tbody.firstChild);
			}
			switch(tbl) {
				case (this.tCommon):
					var players = this.players;
					break;

				case (this.tCustom):
					this.updateCustomList();
					var players = this.customPlayers;
					break;
			}
			players = players.sortBy( function(p) {
				var attr = tbl.getAttribute("SortBy");
				var val = p.getAttribute(attr);
				if (p.getAttribute("CurPos") == "WD") return 10000000;
				switch(attr) {
					case "CurPos":
					case "CurParRel":
					case "TournParRel":
						if (val=="E") { return 0; }
						if (val=="F") { return 10000000; }
						return  parseInt(val.replace( /[A-Z\+]/, ""));
						break;

					case "Fname":
					case "Lname":
						return val.toLowerCase();
						break;


					case "Rnd_Num_1":
					case "Rnd_Num_2":
					case "Rnd_Num_3":
					case "Rnd_Num_4":
					case "Rnd_Num_5":
						var rnd = parseInt(attr.substr(attr.lastIndexOf("_") + 1));
						var val = 0;
						var rounds = $A(p.getElementsByTagName("Rnd"));
						rounds.each( function(r) { if (parseInt(r.getAttribute("Num")) == rnd) { val = parseInt(r.getAttribute("Stroke")); throw $break; } } );
						return val;
						break;

					default:
						return parseInt(val);
						break;
				}
			}.bind(this) );

			var dir = tbl.getAttribute("SortDir")
			if (dir=="desc") players.reverse();
			var count = 0;
			if (hideLeader && reqPID) {
				players = this.players.findAll( function(p) {return p.getAttribute("PID")==reqPID} );
			}
			players.each( function(p) {
				var odd = (count % 2 == 0);
				var row = this.buildPlayerRow(p, odd, tbl);
				var nRow = tbody.appendChild(row);
				var PID = p.getAttribute("PID");
				if (!hideLeader && reqPID && reqPID==PID) this.activeRow = nRow;
				count++;
			}.bind(this));
			if (count > 0) {
				tbl.parentNode.style.display = "block";
			} else {
				tbl.parentNode.style.display = "none";
			}
		},

		buildPlayerRow : function(player, odd, tbl)  {
			var count = 0;
			var c = (odd) ? "odd" : "even";
			var row = this.buildElem("tr", c);
			var PID = player.getAttribute("PID");
			row.setAttribute("PID", PID);
			var isCustom = (this.customCookieValue != "") && (this.customCookieValue).indexOf(PID) != -1;
			var className = "add_del replace";
			className += (isCustom) ? " added" : "";
			var td  = this.buildElem("td", className);
			var a = this.buildElem("a");
			a.href="#";
			var span = this.buildElem("span");
			span.appendChild(document.createTextNode("Add"));
			a.appendChild(span);
			if (tbl == this.tCommon) {
				a.title = "Add";
				Event.observe(a, "click", (function(e) {
					this.moveToCustom(e);
					Event.stop(e);}).bind(this)
				);
			} else if (tbl == this.tCustom) {
				a.title = "Del";
				Event.observe(a, "click", (function(e) {
					this.moveToCommon(e);
					Event.stop(e);}).bind(this)
				);
			}
			td.appendChild(a);
			row.appendChild(td);

			td  = this.buildElem("td");
			td.appendChild(document.createTextNode(player.getAttribute("CurPos")));
			row.appendChild(td);

			td  = this.buildElem("td", "l");
			a = this.buildElem("a");
			a.href="#";
			Event.observe(a, "click", (function(e) {
				this.showScoreCard(e);
				Event.stop(e);}).bind(this)
			);
			var pName = player.getAttribute("Fname") + "&nbsp;" + player.getAttribute("Lname");
			a.innerHTML = pName;
			if (this.numCourses > 1) {
				var crsName = this.courseName[player.getAttribute("CrsCode")] ;
			}
			td.appendChild(a);
			if (typeof crsName != typeof undefined) {
				var span = this.buildElem("span");
				span.innerHTML = crsName.replace(/ /g, "&nbsp;");
				td.appendChild(span);
			}
			row.appendChild(td);

			td  = this.buildElem("td");
			var img = this.buildElem("img");
			img.height = "20";
			var cty = player.getAttribute("country").toUpperCase();
			if (cty) {
				img.src = this.imgFlagPath + player.getAttribute("country").toUpperCase() + ".jpg";
				img.alt = player.getAttribute("country");
			} else {
				img.src = "http://img.timeinc.net/golf/static/img/1x1.gif";
				img.alt = "unknown";
				img.width  = "30";
			}
			td.appendChild(img);
			row.appendChild(td);

			if (player.getAttribute("Thru") == "") {
				td  = this.buildElem("td");
				td.colSpan = 2;
				td.appendChild(document.createTextNode(player.getAttribute("TTimeEST")));
				row.appendChild(td);
			} else {
				td  = this.buildElem("td");
				td.appendChild(document.createTextNode(player.getAttribute("CurParRel")));
				row.appendChild(td);
	
				td  = this.buildElem("td");
				td.appendChild(document.createTextNode(player.getAttribute("Thru")));
				row.appendChild(td);
			}

			td  = this.buildElem("td", "total");
			td.appendChild(document.createTextNode(player.getAttribute("TournParRel")));
			row.appendChild(td);

			var rounds = $A(player.getElementsByTagName("Rnd"));
			for (var i = 0; i < this.numRounds; i++) {
				var td = this.buildElem("td")
				try {
					var val = rounds[i].getAttribute("Stroke");
				} catch (e) {
					var val = this.nbsp;
				}
				td.innerHTML = (val) ? val : this.nbsp;
				row.appendChild(td);
			}
			td  = this.buildElem("td", "total");
			td.appendChild(document.createTextNode(player.getAttribute("TournStrk")));
			row.appendChild(td);

/* Use this var to determine which players to add to tour analyzer if no favourites selected */
			count++;

			return row;
		},

		updateCustomList : function() {
			this.customPlayers = this.players.findAll( function(p) {
				return (this.customCookieValue && this.customCookieValue.indexOf(p.getAttribute("PID")) != -1)
			}.bind(this));
		},

		moveToCustom : function(e) {
			var link = Event.findElement(e, "a");
			var row = Event.findElement(e, "tr");
			var cell = Event.findElement(e, "td");
			var PID = row.getAttribute("PID");

			if (!this.customCookieValue || (this.customCookieValue && this.customCookieValue.indexOf(PID) == -1)) {
				var newCookieValue = (this.customCookieValue == "") ? PID : this.customCookieValue + "," + PID;
				this.eraseCookie(this.customCookieName);
				this.createCookie(this.customCookieName, newCookieValue, this.customCookieDays);
				this.customCookieValue = this.readCookie(this.customCookieName);
				Element.addClassName(cell, "added");
				this.drawTable(this.tCustom);
			}
			addPlayer(PID, newCookieValue.split(",").length);
			link.blur();
		},

		moveToCommon : function(e) {
			var link = Event.findElement(e, "a");
			var row = Event.findElement(e, "tr");
			var PID = row.getAttribute("PID");

			var newCookie = this.customCookieValue.split(",");

/* TO-DO: Determine required result if this is last custom entry */
			if (newCookie.length > 0) {
				newCookie = newCookie.findAll( function(c) { return c != PID } );
				var newCookieValue = newCookie.join(",") + "";
				this.eraseCookie(this.customCookieName);
				this.createCookie(this.customCookieName, newCookieValue, this.customCookieDays);
				this.customCookieValue = this.readCookie(this.customCookieName);
				if (row.getAttribute("showing")=="showing") row.parentNode.removeChild(row.nextSibling);
				row.parentNode.removeChild(row);
				this.drawTable(this.tCommon);
			}
			var num = (this.customCookieValue == "") ? 0 : this.customCookieValue.split(",").length;
			removePlayer(PID, num);
			link.blur();

		},

		showScoreCard : function(e) {
			var link = Event.findElement(e, "a");
			var row = Event.findElement(e, "tr");
			if (row.getAttribute("showing")=="showing" && row.nextSibling && row.nextSibling.className && row.nextSibling.className == row.className) {
				row.parentNode.removeChild(row.nextSibling);
				row.setAttribute("showing", "no");
			} else {
				var tb = Event.findElement(e, "tbody");
				var PID = row.getAttribute("PID");
				var cn  = row.className;
				var nextRow = row.nextSibling;
				link.blur();
				this.getScoreCard(row, cn, PID, tb, nextRow);

				// setting showing should be here not readScoreCard
				// readScoreCard can be an asynchronous call which
				// double-clicking was causing problems when it was there
			  	row.setAttribute("showing", "showing");
			}
			Event.stop(e);
		},

		getScoreCard : function(row, cn, PID, tb, nextRow) {
			if (!this.scoreCards[PID] || !this.scoreCards[PID].xml) {
				if (PID && cn && ((nextRow && !Element.hasClassName(nextRow, cn))) || !nextRow) {
					if (this.folder) {
						this.scoreCards[PID] = new leaderReader(this.folder, "scorecard_" + PID + ".xml");
						this.scoreStats[PID] = new leaderReader(this.folder, "tourn_stats_" + PID + ".xml", true);
						this.handle2 = window.setInterval ( function() { this.readScoreCard(row, cn, PID, tb, nextRow); }.bindAsEventListener(this), 100);
					}
				}
			} else { this.readScoreCard(row, cn, PID, tb, nextRow); }
		},

		readScoreCard : function(row, cn, PID, tb, nextRow) {
			if (this.scoreCards && this.scoreCards[PID].xml) {
				window.clearInterval(this.handle2);
				if (hideLeader) { this.buildPopup(row, cn, tb, PID); return; }
				var retval = this.buildScoreCard(row, cn, PID);
				if(retval) {
					var raw = row.cloneNode(false);
					raw.setAttribute("PID", PID);
					if (nextRow)  { var r = row.parentNode.insertBefore(raw, nextRow); }
					else { var r = row.parentNode.appendChild(raw); }
					var tx = document.createElement("td");
					tx.setAttribute("colSpan", "12");
					var t = r.appendChild(tx);
					var s = (retval.row).getElementsByTagName("td")[0].innerHTML;
					t.innerHTML = s;
					var td = $(retval.cell_id);
					td.setAttribute("rowSpan", retval.rows);
					td.setAttribute("colSpan", 3);

					var links = document.getElementsByClassName("closeScoreCard", t)
					Event.observe(links[0], "click", function(e) {
						var tr = Event.findElement(e, "tr");
						var r = tr.previousSibling;
						tr.parentNode.removeChild(tr);
						r.setAttribute("showing", "no");
						Event.stop(e);
					})

					var links = document.getElementsByClassName("view-full", t)
					Event.observe(links[0], "click", (function(e) {
						this.buildPopup(row, cn, tb, PID);
						Event.stop(e);
					}.bind(this)))
				}
			}
		},

		buildScoreCard : function(row, cn, PID, bFull) {
			var players = (this.scoreCards[PID].xml.getElementsByTagName("Player"));
			var player = null;
			for (var i = 0; i < players.length; i++) {
				var p = players[i];
				if (p.getAttribute("PID")==PID) {
					player = p;
					break;
				}
			}
			if (!player) return;
			var rowCount = 0;
			if (!bFull) {
				var img = this.buildElem("img");
				img.width = "66";
				img.height = "105";
				img.src = this.imgPlayerPath + PID + "_" + img.width + "x" + img.height + ".jpg";
				img.alt = "";
				var a = this.buildElem("a");
				a.href = "/golf/tours_news/playerdetails/0,28352,"+ PID +",00.html";
				a.innerHTML = "Player Details";
				var td  = this.buildElem("td", "headshot");
				td.className = "headshot";
				td.id = "TD_" + PID;
				td.setAttribute("rowSpan", "6");
				td.appendChild(img);
				td.appendChild(a);
			}
			var rowStyle = cn;

/* Deliverable Issue # 3 & 4 */
			var tr = this.buildElem("tr", rowStyle + " hole");
			var tb = this.buildElem("table");
			if (bFull != true) {
				tr.appendChild(td);
			} else {
				var pName = player.getAttribute("Fname") + "&nbsp;" + player.getAttribute("Lname");
				var th  = this.buildElem("th");
				th.innerHTML  = "&nbsp;";
				var tr = this.buildElem("tr", rowStyle);
				tr.appendChild(th);
				th  = this.buildElem("th", "playerNameTitle");
				th.innerHTML = pName + "<br />" + this.tourName;
				th.colSpan = "21"
				tr.appendChild(th);
				tb.appendChild(tr); rowCount++;
				rowStyle = (rowStyle=="odd") ? "even" : "odd";
				var tr = this.buildElem("tr", rowStyle);
			}

			var th = this.buildElem("th");
			th.innerHTML = "Hole:";

			tr.appendChild(th);
			for (var i = 1; i <= 18; i++) {
				td = this.buildElem("td");
				td.innerHTML = i;
				tr.appendChild(td);
				if (bFull) {
					if (i == 9) {
						td = this.buildElem("td");
						td.innerHTML = "OUT";
						tr.appendChild(td);
					} else if (i == 18) {
						td = this.buildElem("td");
						td.innerHTML = "IN";
						tr.appendChild(td);
						td = this.buildElem("td");
						td.innerHTML = "TOTAL";
						tr.appendChild(td);
					}
				}

			}
			tb.appendChild(tr); rowCount++;

			var rounds = $A(player.getElementsByTagName("Rnd"));
			// reverse is needed for all bFull
			if (bFull) {
				// BL - print the rounds in order if displaying all
		      	     rounds.reverse();
			}
			var crs = "";
			rounds.each( function(r) {
				var rNum = r.getAttribute("Num");
				
				if (rNum < this.currRound && bFull != true) { throw $break; }
				var holes = $A(r.getElementsByTagName("Hole"));
				var nextCrs = r.getAttribute("CrsCode");
				if ( nextCrs != crs ) {
					crs = nextCrs;
					rowStyle = (rowStyle=="odd") ? "even" : "odd";
					tr = this.buildElem("tr", rowStyle);
					th = this.buildElem("th");
					th.innerHTML = "Par:";
					tr.appendChild(th);
					var total = 0;
					var totalIN = 0;
					var totalOUT = 0;
					holes.each( function(h, i) {
						td = this.buildElem("td");
						var par = h.getAttribute("Par");
						total += parseInt(par);
						td.innerHTML = par;
						tr.appendChild(td);
						if (bFull) {
							if (i+1 == 9) {
								totalIN = total;
								total = 0;
								td = this.buildElem("td", "total");
								td.innerHTML = totalIN;
								tr.appendChild(td);
							} else if (i+1 == 18) {
								totalOUT = total;
								total = totalIN + totalOUT;
								td = this.buildElem("td", "total");
								td.innerHTML = totalOUT;
								tr.appendChild(td);
								td = this.buildElem("td", "total");
								td.innerHTML = total;
								tr.appendChild(td);
							}
						}
					}.bind(this) );
					tb.appendChild(tr); rowCount++;

					rowStyle = (rowStyle=="odd") ? "even" : "odd";
					tr = this.buildElem("tr", rowStyle);
					th = this.buildElem("th");
					th.innerHTML = "Yards:";
					tr.appendChild(th);
					var holes = $A(r.getElementsByTagName("Hole"));
					var total = 0;
					var totalIN = 0;
					var totalOUT = 0;
					holes.each( function(h, i) {
						var yds = h.getAttribute("ydsOfficial");
						total += parseInt(yds);
						td = this.buildElem("td");
						yds = (yds) ? yds : this.nbsp;
						td.innerHTML = yds;
						tr.appendChild(td);
						if (bFull) {
							if (i+1 == 9) {
								totalIN = total;
								total = 0;
								td = this.buildElem("td", "total");
								td.innerHTML = totalIN;
								tr.appendChild(td);
							} else if (i+1 == 18) {
								totalOUT = total;
								total = totalIN + totalOUT;
								td = this.buildElem("td", "total");
								td.innerHTML = totalOUT;
								tr.appendChild(td);
								td = this.buildElem("td", "total");
								td.innerHTML = total;
								tr.appendChild(td);
							}
						}
					}.bind(this) );
					tb.appendChild(tr); rowCount++;
				}

				rowStyle = (rowStyle=="odd") ? "even" : "odd";
				tr = this.buildElem("tr", rowStyle);
				th = this.buildElem("th");
				th.innerHTML = "R" + this.nbsp + rNum + ":";
				tr.appendChild(th);
				var total = 0;
				var totalIN = 0;
				var totalOUT = 0;
				holes.each( function(h, i) {
					var score = parseInt(h.getAttribute("Score"));
					total += score;
					td = this.buildElem("td");
					var hpar = parseInt(h.getAttribute("Score")) - parseInt(h.getAttribute("Par"));
					var cn = "";
					if (hpar == -2 ) cn = this.scoreCard.Eagles[1]
					else if (hpar == -1 ) cn = this.scoreCard.Birdies[1]
					else if (hpar == 1 ) cn = this.scoreCard.Bogeys[1]
					else if (hpar >= 2 ) cn = this.scoreCard.DoubleBogeys[1]
					td.innerHTML = h.getAttribute("Score");
					Element.addClassName(td, cn);
					tr.appendChild(td);
					if (bFull) {
						if (i+1 == 9 ) {
							totalIN = total;
							total = 0;
							td = this.buildElem("td", "total");
							td.innerHTML = totalIN;
							tr.appendChild(td);
						} else if (i+1 == 18) {
							totalOUT = total;
							total = totalIN + totalOUT;
							td = this.buildElem("td", "total");
							td.innerHTML = totalOUT;
							tr.appendChild(td);
							td = this.buildElem("td", "total");
							td.innerHTML = total;
							tr.appendChild(td);
						}
					}
				}.bind(this) );
				tb.appendChild(tr); rowCount++;
			}.bind(this) );
/* Deliverable Issue # 3 & 4 END */


			tr = this.buildElem("tr", "summary");
			var width = "19";
			var test = this.players.findAll( function(i) {return i.getAttribute("PID")==PID} );

			// show Todays Round if its not finished and !hideLeader
			if (this.scoreStats && !this.scoreStats[PID].failed && this.scoreStats[PID].xml) {
			     if (test[0].getAttribute("Thru")!="F" && !hideLeader) {
				var stats = $A(this.scoreStats[PID].xml.getElementsByTagName("Stat"));
				if (stats) {
					width = "6";
					th = this.buildElem("th");
					tr.appendChild(th);
					td = this.buildElem("td", "round");
					td.setAttribute("colSpan", "12");
					var lbl = this.buildElem("label");
					lbl.innerHTML = "Today's Round:";
					td.appendChild(lbl);
					stats.each( function(stat) {
						var name = stat.getAttribute("Name");
						switch(name) {
							case "Driving Distance Avg":
								var tag = "Driving Distance"
								break;

							case "Fairways Hit":
								var tag = "Driving Accuracy"
								break;

							case "GIR":
								var tag = "Greens in regulation"
								break;

							default:
								break;
						}
						if (typeof tag != typeof undefined) {
							var val = stat.getAttribute("TValue");
							var span = this.buildElem("span");
							span.innerHTML = tag + ": " + val;
							td.appendChild(span);
						}
					}.bind(this));
					tr.appendChild(td);
				}
			    }
			}

/* TO-DO: Replace with link to full scorecard */
			if (bFull != true) {
				td = this.buildElem("td", "hole");
				td.setAttribute("colSpan", width);
				var link = this.buildElem("a", "view-full");
				link.href = "#";
				link.innerHTML = "View Full Scorecard";
				link.title = "View Full Scorecard";
				td.appendChild(link);
				tr.appendChild(td);
			}
			tb.appendChild(tr); rowCount++;rowCount++;

			var div = this.buildElem("div", "scorecard");
			div.appendChild(tb);
			rowCount = tb.getElementsByTagName("tr").length;
			var div2 = this.buildElem("div", "close");
			var div3 = this.buildElem("div", "legend");
			var lbl = this.buildElem("label");
			lbl.innerHTML = "Scorecard: ";
			div3.appendChild(lbl);
			for (itm in this.scoreCard) {
				var txt = this.scoreCard[itm][0];
				var lbl = this.buildElem("label");
				lbl.innerHTML = txt;
				var box = this.buildElem("span");
				box.className = this.scoreCard[itm][1]
				div3.appendChild(box);
				div3.appendChild(lbl);
			}
			div2.appendChild(div3);
			if (bFull != true) {
				var a = this.buildElem("a", "closeScoreCard");
				a.href="#";
				a.innerHTML = "Close scorecard";
				div2.appendChild(a);
			}
			div.appendChild(div2);

			td = this.buildElem("td", 'container');
			td.setAttribute("colSpan", "12");
			td.appendChild(div);
			var scRow = row.cloneNode(false);
			scRow.appendChild(td);
			return { row: scRow, rows: rowCount, cell_id: "TD_"+PID } ;
		},

		buildPopup : function(row, cn, tb, PID) {
			// BL - throw popup and fill in content
			var popRet = this.buildScoreCard(row, cn, PID, true);
			if (popRet) {
				var size = Element.getDimensions(this.container);
				var width = size.width + 16;
				var height = 280;
				var s = (popRet.row).getElementsByTagName("td")[0].innerHTML;
				scorecardData = s;
				var popup = window.open('/golf/tours_news/leaderboard/popup/0,,,00.html?PID='+PID, 'scorecard','height='+height+',width='+width);
			}
			if(hideLeader) {
				var pNode = row.parentNode;
				pNode.innerHTML = "";
			}

		},

/* Utility functions */
		buildElem : function(type, className) {
			var el = document.createElement(type);
			if (className) el.className = className;
			return el;
		},

		createCookie : function(name,value,days){
			if (days){
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},

		readCookie : function(name){
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++){
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return "";
		},

		eraseCookie : function(name) {
			this.createCookie(name,"",-1);
		},

		test : function() {
			this.testReader = new leaderReader(this.folder, "ModifiedLeaderboard.xml");
			this.handle2 = window.setInterval(function() {this.update();}.bind(this), this.interval);
		},

		update : function() {
			if (this.testReader.text && this.testReader.text != this.text) {
				window.clearInterval(this.handle2)
				this.initialize(this.testReader, this.folder);
			}
		}
	}

	var toptenLeaderWidget = Class.create();
	toptenLeaderWidget.prototype = {

		handle1    : null,
		handle2    : null,
		interval   : 5 * 60 * 1000,
		testReader : null,
		xml        : null,
		text       : null,
		folder     : "",
		nbsp       : "&#160;",

		headerRegion  : null,
		hTourName     : null,
		atourInfo     : null,
		tCommon       : null,
		commonSortBy  : "SortIndex",
		tCustom       : null,
		customSortBy  : "SortIndex",
		sortDir       : {asc: "asc", desc: "desc"},
		imgFlagPath   : "http://img.timeinc.net/golf/static/img/leaderboard/flags/",
		imgPlayerPath : "http://img.timeinc.net/golf/static/img/stats/players/",
		activeRow     : null,

		tourNode      : null,
		tourName      : "",
		players       : null,
		customPlayers : null,
		numRounds     : 0,
		tournID       : "",
		scoreCards    : [],
		scoreStats    : [],
		courseName    : [],

		customCookieName      : "",
		customCookieValue     : "",
		customCookiedays      : 10,
		customSortCookieName  : "",
		customSortCookieValue : "",
		commonSortCookieName  : "",
		commonSortCookieValue : "",
		analyzerDefaultCount  : 3,

		initialize : function(reader, folder) {
			try {
				/* define required page elements */
				this.headerRegion = document.getElementsByClassName("lboard-header")[0];
				this.container = $("lboard-container");
				this.hTourName = this.headerRegion.getElementsByTagName("h2")[0];
				this.atourInfo = $A(this.headerRegion.getElementsByTagName("li"));
				this.tCommon = document.getElementsByClassName("lboard-all")[0].getElementsByTagName("table")[0];
				this.tCommon.setAttribute("SortBy", this.commonSortBy);
				this.tCommon.setAttribute("SortDir", this.sortDir.asc);

				// values are left over from prevous object. these need to
				// be initialized
			    	this.scoreCards = [];
			    	this.scoreStats = [];
			    	this.courseName =[];
			    	this.tournID = "";
			    	this.tourNode = null;
			    	this.tourName = null;

				/* capture required data elements */
				this.xml = reader.xml;
				this.text = reader.text;
				this.folder = folder;
				this.players = $A(this.xml.getElementsByTagName("Player"));
				this.drawHeading();
				this.drawTable(this.tCommon);
				if (this.activeRow) this.activeRow.scrollIntoView(true);
				this.handle = window.setInterval(function() {this.test();}.bind(this), this.interval);
			} catch(e) {/* discard error(s) */}
		},

		drawHeading : function() {
			this.tourNode = this.xml.getElementsByTagName("Tourn")[0];
			this.tournId = this.tourNode.getAttribute("TournId");
			this.tourName = this.tourNode.getAttribute("Name");
			this.hTourName.innerHTML = this.tourNode.getAttribute("Name");
			var loc = this.tourNode.getAttribute("Loc");
			loc += (this.tourNode.getAttribute("localCity")) ? ", " + (this.tourNode.getAttribute("localCity")) : "";
			loc += (this.tourNode.getAttribute("LocState")) ? ", " + (this.tourNode.getAttribute("LocState")) : "";
			var links = this.atourInfo[0].getElementsByTagName("span");
			links[0].innerHTML = loc;
			for (var i = 1; i < links.length; i++) {
				this.atourInfo[0].removeChild(this.atourInfo[0].getElementsByTagName("span")[1]);
			}
			this.courses = $A(this.xml.getElementsByTagName("Course"));
			this.atourInfo[1].getElementsByTagName("span")[0].innerHTML = this.tourNode.getAttribute("TournStartDate");
			this.atourInfo[2].getElementsByTagName("span")[0].innerHTML = this.tourNode.getAttribute("Purse");
			this.numRounds = this.tourNode.getAttribute("NumRnds");
			this.numCourses = this.courses.length;
			this.currRound = this.tourNode.getAttribute("CurRnd").substr(0,1);
		},

		drawTable : function(tbl) {
			/* Only draw table header if required */
			if (!hideLeader) {
				var thead = $A(tbl.getElementsByTagName("thead"))[0];
				if (!tbl.getAttribute("headerEvents")) {
					var hLinks = $A(thead.getElementsByTagName("a"));
					hLinks.each( function(a) {
						a.setAttribute("sortDir", this.sortDir.asc);
						Event.observe(a, "click", (function(e) {
							var el = Event.findElement(e, "a");
							var attr = el.href.substr(el.href.lastIndexOf("/") + 1);
							var tb = Event.findElement(e, "table");
							tb.setAttribute("SortBy", attr);
							var sd = el.getAttribute("SortDir");
							tb.setAttribute("SortDir", sd);
							this.drawTable(tb)
							sd = (sd==this.sortDir.asc) ? this.sortDir.desc : this.sortDir.asc;
							el.setAttribute("sortDir", sd);
							Event.stop(e);
						}).bindAsEventListener(this))
					}.bind(this) );
					var roundRow = document.getElementsByClassName("sub", thead)[0];
					for (var i = 0; i < this.numRounds; i++) {
						var th = this.buildElem("th")
						//var a = this.buildElem("a");
						var rnd = parseInt(i + 1,10);
						//a.href = "Rnd_Num_" + rnd;
						//a.innerHTML = rnd;
						//th.appendChild(a);
						th.appendChild(document.createTextNode(rnd));
						roundRow.appendChild(th);
					}
					tbl.setAttribute("headerEvents", "true");
				}
			}

			var tbody = $A(tbl.getElementsByTagName("tbody"))[0];
			while(tbody.childNodes.length) {
				tbody.removeChild(tbody.firstChild);
			}
			var players = this.players;
			players = players.sortBy( function(p) {
				var attr = tbl.getAttribute("SortBy");
				var val = p.getAttribute(attr);
				if (p.getAttribute("CurPos") == "WD") return 10000000;
				switch(attr) {
					case "CurPos":
					case "CurParRel":
					case "TournParRel":
						if (val=="E") { return 0; }
						if (val=="F") { return 10000000; }
						return  parseInt(val.replace( /[A-Z\+]/, ""));
						break;

					case "Fname":
					case "Lname":
						return val.toLowerCase();
						break;

					case "Rnd_Num_1":
					case "Rnd_Num_2":
					case "Rnd_Num_3":
					case "Rnd_Num_4":
					case "Rnd_Num_5":
						var rnd = parseInt(attr.substr(attr.lastIndexOf("_") + 1),10);
						var val = 0;
						var rounds = $A(p.getElementsByTagName("Rnd"));
						rounds.each( function(r) { if (parseInt(r.getAttribute("Num"),10) == rnd) { val = parseInt(r.getAttribute("Stroke")); throw $break; } } );
						return val;
						break;

					default:
						return parseInt(val);
						break;
				}
			}.bind(this) );

			var dir = tbl.getAttribute("SortDir")
			if (dir=="desc") players.reverse();
			var count = 0;
			players.each( function(p) {
				var odd = (count % 2 == 0);
				var row = this.buildPlayerRow(p, odd, tbl);
				var nRow = tbody.appendChild(row);
				var PID = p.getAttribute("PID");
				if (!hideLeader && reqPID && reqPID==PID) this.activeRow = nRow;
				count++;
			}.bind(this));
		},

		buildPlayerRow : function(player, odd, tbl)  {
			var count = 0;
			var c = (odd) ? "odd" : "even";
			var row = this.buildElem("tr", c);
			var PID = player.getAttribute("PID");
			row.setAttribute("PID", PID);
			
			td  = this.buildElem("td");
			td.appendChild(document.createTextNode(player.getAttribute("CurPos")));
			row.appendChild(td);

			td  = this.buildElem("td", "l");
			var pName = player.getAttribute("Fname") + " " + player.getAttribute("Lname");
			td.appendChild(document.createTextNode(pName));
			row.appendChild(td);

			td  = this.buildElem("td");
			var img = this.buildElem("img");
			img.height = "20";
			var cty = player.getAttribute("country").toUpperCase();
			if (cty) {
				img.src = this.imgFlagPath + player.getAttribute("country").toUpperCase() + ".jpg";
				img.alt = player.getAttribute("country");
			} else {
				img.src = "http://img.timeinc.net/golf/static/img/1x1.gif";
				img.alt = "unknown";
				img.width  = "30";
			}
			td.appendChild(img);
			row.appendChild(td);

			 if (player.getAttribute("Thru") == "") {
                                td  = this.buildElem("td");
                                td.colSpan = 2;
                                td.appendChild(document.createTextNode(player.getAttribute("TTimeEST")));
                                row.appendChild(td);
                        } else {
                                td  = this.buildElem("td");
                                td.appendChild(document.createTextNode(player.getAttribute("CurParRel")));
                                row.appendChild(td);
                                td  = this.buildElem("td");
                                td.appendChild(document.createTextNode(player.getAttribute("Thru")));
                                row.appendChild(td);
                        }

			td  = this.buildElem("td", "total");
			td.appendChild(document.createTextNode(player.getAttribute("TournParRel")));
			row.appendChild(td);

			var rounds = $A(player.getElementsByTagName("Rnd"));
			for (var i = 0; i < this.numRounds; i++) {
				var td = this.buildElem("td")
				try {
					var val = rounds[i].getAttribute("Stroke");
				} catch (e) {
					var val = this.nbsp;
				}
				td.innerHTML = (val) ? val : this.nbsp;
				row.appendChild(td);
			}
			td  = this.buildElem("td", "total");
			td.appendChild(document.createTextNode(player.getAttribute("TournStrk")));
			row.appendChild(td);

			/* Use this var to determine which players to add to tour analyzer if no favourites selected */
			count++;

			return row;
		},

		/* Utility functions */
		test : function() {
                        this.testReader = new leaderReader("current_" + tournCode, "leaderboard_top10.xml", this.numRows);
                        this.handle2 = window.setInterval(function() {this.update();}.bind(this), 250);
                },

		update : function() {
                        if (this.testReader.text && this.testReader.text != this.text) {
                                window.clearInterval(this.handle2)
                                this.tbody.innerHTML = "";
                                this.initialize(this.div, this.testReader, this.numRows);
                        }
                },

		buildElem : function(type, className) {
			var el = document.createElement(type);
			if (className) el.className = className;
			return el;
		}
	}

}

function setHeight(h) {
	h = parseInt(h);
	($("golfChartID")).setAttribute("height", h); // BL - for MSIE's benefit.  This must be run before the container is sized.
	($("analyzer")).style.height = h + "px";
}

function addPlayer(PID, count) {
	try {
		thisMovie("golfChartID").addPlayer(PID);
	} catch(e) {/* discard error(s) */}
	($("analyzer")).style.display = "block";
}

function removePlayer(PID, count) {
	try {
		thisMovie("golfChartID").removePlayer(PID);
	} catch(e) {/* discard error(s) */}
	if (count == 0) {
		($("analyzer")).style.display = "none";
		if (($("analyzer")).nextSibling.nodeType == 1) {
			($("analyzer")).nextSibling.style.display = "none";			
		} else {
			($("analyzer")).nextSibling.nextSibling.style.display = "none";
		}
	}
}

function thisMovie(movieName) {
	return $(movieName);
}

function placeAnalyzer(PIDs, numRounds) {
	// BL - comment: if a PID is set and the data changes between page loads there is some odd behaviour of the Flash and container spacing.
	$("analyzer").style.display = (PIDs == "") ? "none" : "";
	var so = new SWFObject("/golf/static/swf/golfChart_v16.swf", "golfChartID", "641", "100", "8", "#e4ebf2");
	so.addVariable("playerIDs", PIDs);
	so.addVariable("numRoundsTotal", numRounds);
	so.addVariable("path", "/golf/static/xml/leaderboard/" + tournFolder + "/SyndScorecard.xml");
	so.addParam("allowScriptAccess","always");
	so.write("analyzer");
}


//dseldow - 092007 - added check for matchplay and forward user along to matchplay template if found.
function matchPlayRedirect() {
	var t = queryString("TID");
	var fid = queryString("folder");
	if (fid != "false") {
		var reader = new leaderReader(fid, "ModifiedLeaderboard.xml");
	} else {
		if (t == "false") t = "r";
		var reader = new leaderReader("current_" + t, "ModifiedLeaderboard.xml");
	}
	temp = window.setInterval ( function() { waitForXML(reader, matchPlayRedirect1); }, 100);
}

if (typeof Class != "undefined") {
        var matchPlayRedirect1 = Class.create();
        matchPlayRedirect1.prototype = {
                initialize : function(reader) {
                        this.xml = reader.xml;
                        this.text = reader.text;
                        this.tourn = this.xml.getElementsByTagName("Tourn")[0];
                        this.tournCode = this.tourn.getAttribute("TourCode");
                        this.tournFormat = this.tourn.getAttribute("Format");
			this.tournID = this.tourn.getAttribute("TournId");
                        this.time = this.tourn.getAttribute("CurTime");
                        this.year = this.time.substr(this.time.lastIndexOf("/") + 1);
			if (this.tournCode.toLowerCase() == tournCode.toLowerCase()) {
                                tournFolder =  (this.tournCode + this.year + this.tournID);
				if (this.tournFormat == "Match") location.href = "/golf/tours_news/leaderboard/match_play";
			}
                }
        }
}
