/**
 * stat update scripts
 *
 * @Henry Postulart
 * @1.0
 */

var temp = null;
var statistics = [	{title: "Official World Golf Ranking", id:"186", statcol: "1", cols: "Rank,Player,Avg. Points" },
					{title: "FedEx Cup Standings", id:"02395", statcol: "1", cols: "Rank,Player,Points" },
					{title: "PGA Tour Money List", id:"109", statcol: "1", cols: "Rank,Player,Money" },
					{title: "Scoring Average", id:"108", statcol: "1", cols: "Name,Player,Avg.", comment: "Replaces Putts per round; id=108 in h" },
					{title: "Scoring Average", id:"120", statcol: "1", cols: "Name,Player,Avg.", comment: "Replaces Putts per round; id=120 in r" },
					{title: "Driving Distance Average", id:"101", statcol: "1", cols: "Rank,Player,Avg. Yards" },
					{title: "Driving Accuracy Percentage", id:"102", statcol: "1", cols: "Rank,Player,Percentage" },
					{title: "Greens in Regulation Percentage", id:"103", statcol: "1", cols: "Rank,Player,Percentage" },
					{title: "Putting Average", id:"104", statcol: "1", cols: "Rank,Player,Avg." },
					{title: "Scrambling", id:"130", statcol: "1", cols: "Rank,Player,Percentage" },
					{title: "Top 10 Finishes", id:"138", statcol: "1", cols: "Rank,Player,Top 10" },
					{title: "Ryder Cup Points", id:"131", statcol: "1", cols: "Rank,Player,Points" },
					{title: "President's Cup Eligibility (U.S.)", id:"140", statcol: "1", cols: "Rank,Player,Point", comment: "Similar stats also in id=187"  }
]

var readers = new Array(statistics.length);
var oH = new Array(statistics.length);
var tournFolder = "";
var currentYear = new Date().getFullYear();
var getPrevYear = currentYear - 1;
var ret = true, chk = 0;

function chkCurrentStatsYear(statID) {
	var available = false;
	var src = "/golf/static/xml/leaderboard/" + currentYear + "/stats/r" + statID + "_top5.xml";
	var itemfound = new Ajax.Request(src, {
		onSuccess: function(response){
			return available = true;
		},
		asynchronous : false
	});
	ret = available;
	return available;
}


function initStats() {
	var t = queryString("TID") ;
	if (t != "false") tournCode = t.toLowerCase();
	var s = ""
	var div = $("lboard-body");
	if (div && tournCode) {
		for (var i = 0; i < statistics.length; i++) {
				var stat = statistics[i];
				if(stat.id !== "108"){
					var id = stat.id
					s += stat.title + " => File ID : " + id + "\n";
					readers[i] = new xmlReader(div, id, i);
				}
		}

	}
}

function waitForXML(index, handler) {
window.clearInterval(oH[index]);

	if (readers[index].xml) {
		window.clearInterval(oH[index]);
		oH[index] = new handler(readers[index]);
	}
}

if (typeof Class != "undefined") {
	var xmlReader = Class.create();
	xmlReader.prototype = {

		xml         : null,
		text        : null,
		indexHandle : null,
		rootPath    : "/golf/static/xml/leaderboard/",
		src         : null,
		div         : null,
		year		: null,

		initialize : function(div, statID, num) {
			try {
				
				if(chk<1){
					this.year = (!chkCurrentStatsYear(statID)) ? getPrevYear : currentYear;
					chk++
				}
				else {
					this.year = (!ret) ? getPrevYear : currentYear;
				}
				this.src = this.rootPath + this.year + "/stats/" + tournCode + statID + "_top5" + ".xml";
				this.indexHandle = num;
				this.div = div;
				this.getData();
			} catch(e) {}

		},

		getData: function () {
			if (this.src) {
			this.xmlHTTP = new Ajax.Request(this.src, {onSuccess: (this.handlerFunc).bindAsEventListener(this), onFailure: (this.errFunc).bindAsEventListener(this), method: "get"  });
			}
		},

		handlerFunc: function(t) {
			this.xml  = t.responseXML;
			this.text = t.responseText;
			statistics[this.indexHandle].OK = "true";
			new statsTable (this, this.div, this.indexHandle);

		},

		errFunc: function(t) {
			statistics[this.indexHandle].OK = "true";
    		//alert('Error ' + t.status + ' -- ' + t.statusText + ' -- ' + this.src);
		}
	};

	var statsTable = Class.create();
	statsTable.prototype = {

		handle     : null,
		interval   : 5 * 60 * 1000,
		testReader : null,
		count      : 0,

		initialize : function(reader, div, index) {
			if(	statistics[index].OK == "false") return;
			try {
				this.div = div;
				this.reader = reader;
				this.index = index;
				this.numRows = 5;
				this.headerDiv = document.getElementsByClassName("lboard-header", this.div)[0];
				this.contentDiv = document.getElementsByClassName("lboard-all", this.div)[0];
				this.eventHeading = this.headerDiv.getElementsByTagName("h2")[0];
				this.eventDateHeading = this.headerDiv.getElementsByTagName("p")[0];
				this.xml  = reader.xml;
				this.text = reader.text;
				this.tour = this.xml.getElementsByTagName("tour")[0];
				this.year = this.tour.getElementsByTagName("year")[0];
				this.lastTourn = this.year.getElementsByTagName("lastTrnProc")[0];
				this.stat = this.year.getElementsByTagName("stat")[0];
				this.statTitles = this.stat.getElementsByTagName("statTitles")[0];
				this.details = this.stat.getElementsByTagName("details")[0];
				this.players = $A(this.details.getElementsByTagName("plr"));

/* Only display stats with data */
				if (this.players.length) {
					var stat = this.buildTable(this.index);
					this.contentDiv.appendChild(stat);
					if (this.count++ % 2 == 1) {
						this.contentDiv.appendChild(this.buildElem("div", "clearfix"));
					}
					this.eventHeading.innerHTML = this.year.getAttribute("year") + " " + this.tour.getAttribute("tourName");
					this.eventDateHeading.innerHTML = this.lastTourn.getAttribute("endDate");
				}
			} 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);
			}
		},

		buildTable : function(index) {
			// table caption
			var cap = this.buildElem("caption");
			cap.appendChild(document.createTextNode(name));

			// table title
			var div = this.buildElem("div");
			div.appendChild(document.createTextNode(statistics[index].title));
			var th = this.buildElem("th");
			th.setAttribute("colSpan", "3");
			th.appendChild(div);


			var tr = this.buildElem("tr", "header");
			tr.appendChild(th);
			var thd = this.buildElem("thead");
			thd.appendChild(tr);
			var tr = this.buildElem("tr");
			var headings = statistics[this.index].cols.split(",");
			for (var i = 0; i < headings.length; i++) {
				var th = this.buildElem("th");
				if (i == 0) th.className = "center";
				if (i == 2) th.className = "total center";
				th.appendChild(document.createTextNode(headings[i]));
				tr.appendChild(th);
			}
			thd.appendChild(tr);

/* table rows */
			var tbd = this.buildElem("tbody");

			this.players.each( function(player, i) {
				var odd = (i % 2 == 0) ? "odd" : "even";
				var tr = this.buildStatRow(player, i, index, odd)
				tbd.appendChild(tr)
			}.bind(this) );

			/* footer row with link */
			var tr = this.buildElem("tr");
			var td = this.buildElem("td", "footer");
			td.setAttribute("colSpan","3");
			var div = this.buildElem("div", "get-more");
			var a = this.buildElem("a", "more");
			a.href = "#";
			//a.appendChild(document.createTextNode("Full Stats " + statistics[index].title + "..."));
			//div.appendChild(a);
			td.appendChild(div);
			tr.appendChild(td);
			tbd.appendChild(tr);
			var tbl = this.buildElem("table");
			tbl.appendChild(cap);
			tbl.appendChild(thd);
			tbl.appendChild(tbd);
			var div = this.buildElem("div", "stats-bag");
			div.appendChild(tbl);
			return div;
		},

		buildStatRow : function(player, seq, index, odd)  {
			var PID = player.getAttribute("plrNum");
			var pNameNode = player.getElementsByTagName("plrName")[0];
			var pName = pNameNode.getElementsByTagName("first")[0].firstChild.nodeValue + " " + pNameNode.getElementsByTagName("last")[0].firstChild.nodeValue;
			var row = this.buildElem("tr", odd);
			var td  = this.buildElem("td", "center");
			var p = this.buildElem("p", "center");
			p.appendChild(document.createTextNode(seq+1));
			td.appendChild(p);
			row.appendChild(td);
			td  = this.buildElem("td", "player");
			var a = this.buildElem("a");
 			a.href = "/golf/tours_news/playerdetails/0,28352,"+ PID +",00.html";
			a.appendChild(document.createTextNode(pName));
			p = this.buildElem("p");
			p.appendChild(a);
			td.appendChild(p);
			row.appendChild(td);
			td  = this.buildElem("td", "total center");
			p = this.buildElem("p", "center");
			var statval = player.getElementsByTagName("statValue" + statistics[index].statcol)[0].firstChild.nodeValue;
			p.appendChild(document.createTextNode(statval));
			td.appendChild(p);
			row.appendChild(td);
			return row;
		},

/* Utility functions */
		buildElem : function(type, className, attrs) {
			var el = document.createElement(type);
			if (className) el.className = className;
			return el;
		}

	};

}

