/**
 * Fedex Cup Leaderboard scripts
 *
 * @Henry Postulart
 * @1.0
 */

var temp = null;
var oH = new Array();

function findFedexBoard() {
	try {
		var reader = new leaderReader();
		temp = window.setInterval ( function() { waitForXML(reader, this.fedexTable); }, 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 waitForXML(reader, handler) {
	if (reader.xml) {
		window.clearInterval(temp);
		oH[oH.length] = new handler(reader);
	}
}

if (typeof Class != "undefined") {
	var leaderReader = Class.create();
	leaderReader.prototype = {

		xml      : null,
		text     : null,
		rootPath : "/golf/static/xml/leaderboard/",
		file     : "r_02394_countries.xml",
		src      : "",

		initialize : function(file) {
			try {
				if (file) this.file = file;
				this.year = new Date().getFullYear();
				this.src = this.rootPath + this.year + "/stats/" + this.file;
				this.getData(this.src);
			} catch(e) { /* Fail silently */ }

		},

		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) {
			/*  Fail silently
    		alert('Error ' + t.status + ' -- ' + t.statusText + '\n\n' + this.src);
    		*/
		}
	};

	var fedexTable = Class.create();
	fedexTable.prototype = {

		handle1       : null,
		handle2       : null,
		interval      : 5 * 60 * 1000,
		testReader    : null,
		xml           : null,
		text          : null,
		folder        : "",
		nbsp          : "&#160;",
		initialized   : false,

		sortBy        : "curRank",
		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,

		players       : null,
		numRounds     : 0,
		scoreCards    : [],
		scoreStats    : [],
		courseName    : [],

		initialize : function(reader) {
			try {
				this.reader = reader;

				/* define required page elements */
				this.container = $("lboard-container");
				this.div = document.getElementsByClassName("lboard-all", this.container)[0];
				this.table = this.div.getElementsByTagName("table")[0];
				this.tbody = this.table.getElementsByTagName("tbody")[0];


				// 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;

				/* define required data elements */
				this.xml  = reader.xml;
				this.text = reader.text;
				this.players = $A(this.xml.getElementsByTagName("plr"));

				/* Put it all together in the page */
				this.drawTable();

				/* Flag initialization complete */
				this.initialized = true;

				/* set up 5 minute refresh */
				this.handle = window.setInterval(function() {this.test();}.bind(this), this.interval);

			} 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);
			}
		},

		drawTable : function() {

			var tbl = this.table;

			/* Populate table header links with event handlers and title tags */
			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);
					a.title = "Click to sort by " + a.innerHTML ;
					Event.observe(a, "click", (function(e) {
						var el = Event.findElement(e, "a");
						var attr = el.href.substr(el.href.lastIndexOf("/") + 1);
						this.table.setAttribute("SortBy", attr);
						// note the stop is not at the end  drawTable can
						// sometimes take so long that the page gets
						// here before this method has ended.
                        Event.stop(e);
					   	this.drawTable();
					}).bindAsEventListener(this))
				}.bind(this) );
				tbl.setAttribute("headerEvents", "true");
				tbl.setAttribute("sortDir", this.sortDir.asc);
			}

			var tbody = this.tbody;
			while(tbody.childNodes.length) {
				tbody.removeChild(tbody.firstChild);
			}

			var players = this.players;

			if (this.initialized) {
				players = players.sortBy( function(p) {
					var attr = tbl.getAttribute("SortBy");

					switch(attr) {
						case "statValue1":
						case "statValue2":
						case "statValue3":
						case "statValue4":
						case "statValue5":
						case "rndEvents":
							var node = p.getElementsByTagName("statValues")[0].getElementsByTagName(attr)[0];
							var val = "DNP";
							if(node.firstChild) {
								val  = node.firstChild.nodeValue.toUpperCase();
							}
							if (val == "CUT") { return 10000000; }
							if (val == "DNP") { return 20000000; }
							if (val == "W/D") { return 30000000; }
							val = val.replace( /[A-Z\+]/, "");
							val = val.replace( /\$/, "");
							val = val.replace( /\,/g, "");
							return parseInt(val);
							break;

						case "first":
						case "last":
							var val = p.getElementsByTagName("plrName")[0].getElementsByTagName(attr)[0].firstChild.nodeValue;
							if (attr == "last") val = val.substr(val.indexOf(" ") + 1);
							return val.toLowerCase();
							break;

						case "curRank":
							var val = p.getElementsByTagName("curRank")[0].firstChild.nodeValue;
							return parseInt(val);
							break;

						default:
							return  parseInt(val.replace( /[A-Z\+]/, ""));
							break;
					}
					if (val == "undefined") return null;
				}.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);
				var nRow = tbody.appendChild(row);
				count++;
			}.bind(this));
			var newDir = (dir == this.sortDir.asc) ? this.sortDir.desc : this.sortDir.asc;
			tbl.setAttribute("SortDir", newDir);
		},

		buildPlayerRow : function(player, odd)  {
			var count = 0;
			var c = (odd) ? "odd" : "even";
			var row = buildElem("tr", c);
			var PID = player.getAttribute("plrNum");
			row.setAttribute("PID", PID);

			/*  Assemble required data */
			try {

				var curRank = player.getElementsByTagName("curRank")[0].firstChild.nodeValue;
				var curTied = player.getElementsByTagName("curRank")[0].getAttribute("tied");
				if (typeof curTied == typeof undefined) curTied = "";

/* ^^^ Start of temporary */
curTied = '';
/* ^^^ End of temporary */

				var name = player.getElementsByTagName("plrName")[0];
				var fName = name.getElementsByTagName("first")[0].firstChild.nodeValue;
				var lName = name.getElementsByTagName("last")[0].firstChild.nodeValue;
				var n = (fName) ? fName + this.nbsp : "" ;
				n += (lName) ? lName : "";

				var cty = player.getElementsByTagName("country")[0].firstChild.nodeValue.toUpperCase();
				var prevRank = '';
				
				if(player.getElementsByTagName("prevRank")[0].firstChild) {
					prevRank = player.getElementsByTagName("prevRank")[0].firstChild.nodeValue;
				}
				
				if (prevRank == "undefined") prevRank = "";
				var prevTied = player.getElementsByTagName("prevRank")[0].getAttribute("tied");
				if (typeof prevTied == typeof undefined) prevTied = "";

/* ^^^ Start of temporary */
prevTied = '';
/* ^^^ End of temporary */

				var stats = player.getElementsByTagName("statValues")[0];

				var points = safeNodeValue(stats.getElementsByTagName("statValue1")[0], "");
				if (points == "undefined") points = "";
				var events = safeNodeValue(stats.getElementsByTagName("rndEvents")[0], "");
				if (events == "undefined") events = "";
				/*var topTens = safeNodeValue(stats.getElementsByTagName("statValue4")[0], "");
				if (topTens == "undefined") topTens = "";*/
				var wins = safeNodeValue(stats.getElementsByTagName("statValue3")[0], "");
				if (wins == "undefined") wins = "";
				var earnings = safeNodeValue(stats.getElementsByTagName("statValue5")[0], "");
				if (earnings == "undefined") earnings = "";

			} catch(e) {}

			/* Insert row */

			td  = buildElem("td");
			td.appendChild(document.createTextNode(curTied + curRank));
			row.appendChild(td);

			td  = buildElem("td");
			td.appendChild(document.createTextNode(prevTied + prevRank));
			row.appendChild(td);

			td  = buildElem("td", "l");
			a = buildElem("a");

/* TO-DO: TII: construct Player Details URL here */
			a.href="/golf/tours_news/playerdetails/0,28352,"+ PID +",00.html";

			a.innerHTML = n;
			td.appendChild(a);
			row.appendChild(td);

			td  = buildElem("td");
			var img = buildElem("img");
			img.height = "20";
			if (cty) {
				img.src = this.imgFlagPath + cty + ".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);


			td  = buildElem("td");
			td.appendChild(document.createTextNode(points));
			row.appendChild(td);

			td  = buildElem("td");
			td.appendChild(document.createTextNode(events));
			row.appendChild(td);
			
			/*
			td  = buildElem("td");
			td.appendChild(document.createTextNode(topTens));
			row.appendChild(td);
			*/

			td  = buildElem("td");
			td.appendChild(document.createTextNode(wins));
			row.appendChild(td);

			td  = buildElem("td", "total");
			td.appendChild(document.createTextNode(earnings));
			row.appendChild(td);

 			return row;
		},

/* Utility functions */
		test : function() {
			this.testReader = new leaderReader(this.folder, "ModifiedLeaderboard.xml");
			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.initialize(this.testReader, this.folder);
			}
		}
	}

}

