// JavaScript Document
/*
CreateLeaderboard.js Version 1.0 by Ron Harris
Release Notes:

v1.0: 2/23/10
Version 1 of new Leaderboard codebase. This version is Prototype.js independent. Reserved for
the small version of limited functionality. Includes expanded scorecard, full \
ModifiedLeaderboard.json usage, and scrolling table. Current usage include Nerve Center popup
and Homepage/Section front tabbed tool widget.

*/

/* var LB = {};
LB.Tourndata = {};
LB.Tourndata.data = null;
LB.Tourndata.gDate = function () {
	var d = new Date();
	d = d.getFullYear();
	return d
}
LB.Utils = {};
LB.Utils.setCookie = function(cookie_name, val, expire){
	var exdate = new Date();
	var path = '/tours_news/leaderboard/';
	exdate.setDate(exdate.getDate() + expire);
	document.cookie = cookie_name+"="+escape(val)+';path=/'+((expire==null)?'':';expires='+exdate.toGMTString());
}

LB.Utils.getCookie = function ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

LB.Utils.delCookie = function(cookie_name) {
	var path = '/tours_news/leaderboard/';
	document.cookie = cookie_name+'=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

LB.Scoredata = {};
LB.Scoredata.data =  null;
*/


/* Object to contain data and arrays accessible throughout the application */
var LB = {
	openScoreCard : [],
	size : "",
	Tourndata : {
		data : null,
		gDate : function (){
			var d = new Date();
			d = d.getFullYear();
			return d;
		}
	},
	Utils : {
		setCookie : function(cookie_name, val, expire){
			var exdate = new Date();
			var path = '/tours_news/leaderboard/';
			exdate.setDate(exdate.getDate() + expire);
			document.cookie = cookie_name+"="+escape(val)+';path=/'+((expire==null)?'':';expires='+exdate.toGMTString());
		},
		getCookie : function ( cookie_name ){
		  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
		  if ( results )
			return ( unescape ( results[2] ) );
		  else
			return null;
		},
		delCookie : function(cookie_name) {
			var path = '/tours_news/leaderboard/';
			document.cookie = cookie_name+'=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT';
		}
	},
	Scoredata : {
		data : null
	}
};

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function create(elem){
	return document.createElement(elem);
}

/* Build the scorecard. Called on each event that expands the scorecard for each player. Ensures that the lastest scorecard is available when the event is triggered. */
var buildScoreCard = {
	scdata : null,
	curRnd : function(pos){
		return LB.Tourndata.data.Players.Player[pos].CurRnd;
	},
	jsonFile : function(pid){
		var dir = LB.Tourndata.data.TourCode.toLowerCase() + LB.Tourndata.gDate() + LB.Tourndata.data.TournId;
		var jFile = '/golf/static/xml/leaderboard/' + dir + '/scorecard_'+pid+'.json';
		return jFile;
	},
	getData : function (url, pid){
		var jurl = this.jsonFile(pid);
		/* Async is set to false. If true is to be used, onSuccess property has to be used. The the data will have to be managed. */
		var html = jQuery.ajax({type: 'GET', url : jurl, dataType : 'json', async : false, cache : false, error : function(x){ /* No Data display */} }).responseText;
		this.scdata = eval("("+html+")").PlayerScorecard.Player;
	},
	getRounds : function (){
		var rnd = this.scdata.Rnd.length || null;
		return rnd;
	},
	process : function(d, pos){
		var chkPID = '#pid'+d;
		if(jQuery(chkPID).find('table').length > 0){
			//I need to check timestamps on whether I need to update
			return
		}
		var scBody, scRow, scPos, cardPos, rnd = null, total, holes, hole = [], score = [], par = [];
		this.getData(this.jsonFile(d), d);
		var rounds = this.getRounds();
		
		if(rounds){
			var j=0;
			while(--rounds){
				if(this.scdata.Rnd[j].Num === this.curRnd(pos)) {
					rnd = this.scdata.Rnd[j];
					break;
				}
				j++;
			}
		}
		else {rnd = this.scdata.Rnd}
		if(!rnd){
			return	
		}
		var holes = rnd.Hole.length;
		var hole = [], score = [], par = [];
		for(var i=0; i<holes; i++){
			hole[i] = rnd.Hole[i].Num;
			par[i] = rnd.Hole[i].Par;
			score[i] = rnd.Hole[i].Score;
		}
		
		var scoreLen = score.length;
		var vsPar = [];
		var isSmallLB = (LB.size.toLowerCase() === 'small') ? true : false;
		
		if(LB.size.toLowerCase() === 'small'){
			scPos = ((score[8].search(/\d+/) > -1 && score[9].search(/\d+/) > -1) || (score[0].search(/\d+/) == -1 && score[9].search(/\d+/) > -1)) ? 9 : 0;
		} 
		else {
			scPos = 0;	
		}
		
		/* Build the scorecard table with the 3 rows for Hole, Par, and Score. Score's td change BG color depending on value as compared to Par. */
		function createRow (val, txt, opt){
			var sum = 0, scCell, eq=0, i=scPos, len=0, parValue = '', 
				scLength = (isSmallLB) ? 9 : 18;
				
			scCell = scRow.appendChild(create('th'));
			scCell.appendChild(document.createTextNode(txt));
			for(;i<18; i++){
				if(len < scLength){
					if(txt.indexOf('Par')>-1){ vsPar[i] = val[i]; }
					sum = sum + parseInt(val[i])
					scCell = scRow.appendChild(create('td'));
					if(txt.indexOf('Score')>-1){
						switch(vsPar[i] - val[i]){
							case 2:
									parValue = 'eagle';
									break
							case 1:
									parValue = 'birdie';
									break
							case -1:
									parValue = 'bogie';
									break
							case -8:
							case -7:
							case -6:
							case -5:
							case -4:
							case -3:
							case -2:
									parValue = 'dblbogie';
									break
							default:
									parValue = 'par';
						}
						scCell.className = parValue;
					}
					scCell.appendChild((document.createTextNode(val[i]).length < 1) ? document.createTextNode(' ') : document.createTextNode(val[i]) );
				}
				len++;
			}
			scCell = scRow.appendChild(create('td'));
			total = (txt.indexOf('Hole') > -1) ? opt : (sum)? sum : '';
			scCell.appendChild((document.createTextNode(total).length < 1)? document.createTextNode(' ') : document.createTextNode(total));
		}
			
		var sc = create('table');
		sc.className = 'scorecard-tbl';
		sc.setAttribute('cellSpacing','0');
		scBody = sc.appendChild(create('tbody'));
		scard = LB.Tourndata.data.Players.Player[pos].Rnd[LB.Tourndata.data.Players.Player[pos].CurRnd];
		scTotal = (isSmallLB) ? 'Out' : 'Tot'
		cardPos = (scPos > 8) ? 'In': scTotal;
		
		/* Build out each row in order. */
		for(var j=0; j<3; j++){
			scRow = scBody.appendChild(create('tr'));
			switch(j){
				case 0:
					scRow.className = 'holeRow';
					createRow(hole, 'Hole:', cardPos);
					break;
				case 1:
					scRow.className = 'parRow';
					createRow(par, 'Par:', cardPos);
					break
				case 2:
					scRow.className = 'scoreRow';
					createRow(score, 'Score:', cardPos);
					break
				default:
			}
		}
		return sc;
	}
}

var createLB = function (size) {
	/* 100 == British Open; 033 == PGA Championship; 014 == The Masters; 026 == U.S. Open; 011 == The Players Championship (non-Major) */	
	var feed = (contentType === "nervecenter") ? 'r' + LB.Tourndata.gDate() + tournid : 'current_r'; // Change to hard-coded tournament archive directory; ex: r2010004; Use current_[tcode] for testing only if used for one-offs;
	var jsonFile = '/golf/static/xml/leaderboard/'+feed+'/ModifiedLeaderboard.json';
	var pkg = document.createDocumentFragment();
	var nodata = false;
	LB.size = size;
	function callData (int){
		if(int<3){
			var html = jQuery.ajax({
				type: 'GET',
				url : jsonFile,
				dataType : 'json',
				async : false,
				cache : false,
				error : function(x){callData((int + 1))}
			}).responseText;
		}
		return html;
	}

	var loadData = function(){
		try{
			var results = callData(0);
			results = eval("(" + results + ")").Tourn; 
			return results;
		}
		catch(e){
			return null
		}
	}

	try {
		var d = loadData();
		
		/* If specified tournament data is not available, give message below */
		if (!d){
			var msg = document.createElement('p');
			msg.appendChild(document.createTextNode("There is no tournament data at this time. Please check back later for the very latest tournament scores."));
			pkg.appendChild(msg);
			return pkg;
		}
		
		/* For HP/Section Front widget: Builds footer that contains the Full LB link. Differentiates between Current_R and archive directories. */
		var lblink = document.getElementById('lb-widget').getElementsByTagName('th')[0];
		if(lblink.className.toLowerCase() !== 'pos'){
			lblink.innerHTML = (feed == 'current_r') ? '<span></span><a href="/golf/tours_news/leaderboard/" class="fullLink">Full Leaderboard</a>' : '<span></span><a href="/golf/tours_news/leaderboard/0,28360,' + feed + ',00.html?folder=' + feed + '" class="fullLink">Full Leaderboard</a>';
		}
		
		
		LB.Tourndata.data = d;
		
		jQuery('#toolbar-1').find('h2').html('<a href="/golf/tours_news/leaderboard/">' + LB.Tourndata.data.Name + '</a>');
		jQuery('#toolbar-1').find('h4').text('Round ' + LB.Tourndata.data.CurRnd);
		
		
		var row, cell, icon, alink, box, sc, mpid;
		var masterTbl = create('table');
		masterTbl.id = 'lb-widget-content';
		masterTbl.setAttribute('cellSpacing','0');
		pkg.appendChild(masterTbl);
		
		/* Populate Globals for Blog */
		 tournYr = new Date().getFullYear();
		 tournID = d.TournId; 
		 curRound = d.CurRnd;
		 suddenDeath = '';
		 postTournament= (d.CurRndState == 'Official') ? true : false;;
		
		/* Build the top-level score summary. */
		var len = d.Players.Player.length;
		for(var h=0; h<len;h++){
			var player = d.Players.Player[h];
			var pid = player.PID;
			var tbody = create('tbody');
			var tr  = create('tr');
			var td  = create('td');
			var body = masterTbl.appendChild(tbody);
			var classArray = ['pos', 'player', 'today', 'thru', 'tot']
			var getTTime = (player.Thru == '' && player.TTimeEST != '') ? player.TTimeEST : null;
			var getPlayerName = player['Fname'] + " " + player['Lname'];

			if (getPlayerName.length > 10){
				getPlayerName = player['Fname'].substr(0,1) + ". " + player['Lname'] ;
			}
			
			var lbArray = ['CurPos',getPlayerName,'CurParRel','Thru','TournParRel']
			for(var j=0; j<2; j++){
				row = body.appendChild(create('tr'));
				row.className = (h % 2 == 0) ? 'odd':'even';
				if(j<1){
					mpid = 'id' + pid;
					body.id = mpid;
					for(var i=0; i<5; i++){
						cell = row.appendChild(create('td'));
						cell.className = classArray[i];
						if(i===1){
							icon = cell.appendChild(create('span'));
							if(player['CurPos'].toLowerCase().indexOf('wd') && player['CurPos'].toLowerCase().indexOf('cut') && player['CurPos'].toLowerCase().indexOf('mdf') && player['CurPos'].length > 0){
								icon.className = 'plusIcon';
								alink = cell.appendChild(create('a'));
								alink.href = '#';
								alink.appendChild(document.createTextNode(lbArray[i]));
							}
							else {
								icon.className = 'plusIconNSC';
								cell.appendChild(document.createTextNode(lbArray[i]));
							}
						}
						else if(i === 2 && getTTime!=null){
							cell.className = 'ttime';
							cell.colSpan = '2';
							cell.appendChild(document.createTextNode(player['TTimeEST']));
							i++;
						}
						else{
							cell.appendChild(document.createTextNode(player[lbArray[i]] || ' '))
						}
					}
				}
				else {
					row.className = 'scorecard';
					row.id = 'p' + mpid;
					cell = row.appendChild(create('td'));
					cell.setAttribute('colSpan', 5);
					box = cell.appendChild(create('div'));
					box.id = h;
					var cookiePlayer = 'player'+pid;
					/* If scorecard is open, confirm with value in LB.openScoreCard object. Keeps scorecard open on auto-refresh */
					for(i in LB.openScoreCard){
						if(i == mpid){
							icon.style.backgroundPosition = '-9px 0px';
							box.appendChild(LB.openScoreCard[i]);
							box.style.display = 'block';
						}
					}
				/*	if(LB.Utils.getCookie(cookiePlayer)){
						box.style.display = 'block';
					} */
				}
			}
		}
		/* Refreshes data on LB. ReplaceChild prevents reload flicker */
		setTimeout(function(){
			var ParentElem = document.getElementById('master');
			var old = ParentElem.childNodes[0];
			ParentElem.replaceChild(createLB(size), old );
		}, 45000);
	
		return pkg;
	}
	catch (e) {
		throw Error('Something happened in the Table Creation Block')
	}
};

jQuery(function(){
	/* Assign all event listeners on completion of DOM tree creation */
	/* If the opened window (in most cases the Nerve Center) doesn't find its parent window, recreate one. */
	jQuery('#lb-widget').find('.fullLink').live('click', function(e){
		if(window.opener && !window.opener.closed){
			window.opener.location.href = jQuery(this).attr('href');
		}
		else {
			var pw = window.open(jQuery(this).attr('href'),'');
			pw.focus();
		}
		return false
	});	
	
	/* Open Nerve Center Popup window when link (with specific class) is present */
	jQuery('.liveCoverage').click(function(){
		if(!window.golf){
			var nw = window.open('/golf/nc','golf', 'width=728,height=680,left=0,top=0');
		}
		else {
			window.golf.focus();	
		}
		return false;
	});
	
	/* All future created tbody's that have id attributes are given an event listener for the LB functionality */
	jQuery('tbody[id]').live('click', function(e){
		/* If any tbody is found with a TD descendant what has a text node of any of these values, don't apply functionality */									   
		if(jQuery(this).find('.pos').text().toLowerCase().indexOf('cut') && jQuery(this).find('.pos').text().toLowerCase().indexOf('wd') && jQuery(this).find('.pos').text().toLowerCase().indexOf('mdf') && jQuery(this).find('.pos').text().indexOf(' ')<0){
			var sc = jQuery(this).parents('tbody').attr('id') || jQuery(this).attr('id');
			var that = jQuery(this);
			var sdiv = '#p' + sc;
			var pid = sdiv.substr(4,5);
			var num = jQuery(this).parents('tbody').find('div').attr('id') || jQuery(this).find('div').attr('id');
			jQuery(sdiv).find('div').slideToggle('fast', function (){
				if(jQuery(this).is(':visible')){
					var card = buildScoreCard.process(pid, num);
					LB.openScoreCard[sc] = card;
					jQuery(this).append(card);
					that.find('span').css('backgroundPosition','-9px 0px')
					//LB.Utils.setCookie('player'+pid,'expanded',5);
				}
				else {
					that.find('span').css('backgroundPosition','-9px -14px')
					delete LB.openScoreCard[sc];
					jQuery(this).empty();
					//LB.Utils.delCookie('player'+pid);
				}
			});
		}
		return false;
	}).css('cursor','hand');
})