// Add onload event to pre-load custom leaderboard
Event.observe(window, 'load', function() { generateLeaderboardFromCookie(); });

//Adds a row to the customized 'my leaderboard section'
function addRow(myRowId,isPageRefresh)
{
	if (window.event) {
		window.event.cancelBubble = true;
	}

	var the_row = document.getElementById(myRowId);		//The row to be copied
	var newRow = the_row.cloneNode(true);				//The cloned new row
	var myLeaderboardNode = document.getElementById('myLeaderboardBody');	//myLeaderboard table obj

	newRow.id = newRow.id + "_2";		//Change row id so there are not duplicates

	myLeaderboardNode.appendChild(newRow);	//Append new row to table

	if (myLeaderboardNode.getElementsByTagName("tr").length == 1) //If there is at least one row in My Leaderboard
	{
		showTableBodies(myLeaderboardNode);		//Show table bodies and change headers
	}

	alternateRowColor(myLeaderboardNode);	//Make row color alternate
	swapImage(document.getElementById(myRowId), "add_off");		//swap out add image to add off

	if (!isPageRefresh)		//If the page is not being refreshed add the player to the cookie
	{
		addPlayerToCookie(myRowId);		//store row ids in a variable to save in cookie
	}

}

//Displays Myleaderboard Tbody and Table Break Tbody and changes header image when at least one row exists in the myleaderboard table
function showTableBodies(myLeaderboardNode)
{
	if (window.event) {
		window.event.cancelBubble = true;
	}

	document.getElementById('myLeaderboardBody').style.display = '';//Show MyLeaderboard TableBody
	document.getElementById('myLbBreakBody').style.display = '';  //Show Table Break TableBody
	document.getElementById("myLB_header").src = "http://i.pga.com/pga/images/events/template_rev2/img/scoring/my_leaderboard.gif";//Change Table Heading
}

//Hides Myleaderboard Tbody and Table Break Tbody and changes header image when there are no rows in the myleaderboard table
function hideTableBodies()
{
	if (window.event) {
		window.event.cancelBubble = true;
	}

	document.getElementById('myLeaderboardBody').style.display = 'none';	//Hide MyLeaderboard Tbody
	document.getElementById('myLbBreakBody').style.display = 'none';	//Hide tablebody break
	document.getElementById("myLB_header").src = "http://i.pga.com/pga/images/events/template_rev2/img/scoring/build_your_own_leaderboard.gif";//Change Table Heading
}

// Add function for auto-complete form
function autocompleter_add() {
	var row_id = name_lookup[document.getElementById('player_search').value];
	var myCurrentPlayers = getCookie('cMyLeaderboard');	//get cookie values

	if(myCurrentPlayers)
	{
		// Add the player only if not already present
		if (myCurrentPlayers.search(row_id) == -1) {
			addRow(row_id, false);
		}
	}
	else
	{
		addRow(row_id, false);
	}

	document.getElementById('player_search').value = "";
}

//Alternates the color of the rows
function alternateRowColor(myLeaderboardNode)
{
	if (myLeaderboardNode.hasChildNodes())		//If myLeaderboard has child nodes
	{
	   var children = myLeaderboardNode.childNodes;		//Reference to childnodes
	   var count = 0;									//Count used to track # of rows to assist in alternating the colors
	   var myChildNodeImg;								//Stores img in child node


	   for (var i = 0; i < children.length; i++) 		//Loop through the children of myLeaderboard
	   {

			if(children[i].nodeName == "TR"){		//find TR's
				count = count + 1;

				if (children[i].hasChildNodes())  //If the TR has children find image and swap it out
				{
						swapImage(document.getElementById(children[i].id), "remove");	//swap out images
				}
				if(count%2 > 0)	//if even row number style one way
				{
					children[i].className = "tint";
				}
				else //remove style
				{
					children[i].className = "";
				}
			}
	   };
	 };
}

//swapes our images / class attributes / onClick event for the image button
function swapImage(objChild, newImageName)
{
	//get the 1st image node from the tr
	var myChildNodeImg = objChild.getElementsByTagName("img")[0];
	var myChildNodeA = objChild.getElementsByTagName("a")[0];

	//replace image
	switch (newImageName) {
		case "remove":
				//change image url
				myChildNodeImg.src = "http://i.pga.com/pga/images/events/template_rev2/img/scoring/btn_remove.gif";
				//change onClick Event
				myChildNodeA.onclick =
			    function() {
			     onClick=removeRow(this.parentNode.parentNode.id);
			     return false;
			    }
				myChildNodeA.className = "";
				break;
		case "add":
				myChildNodeImg.src = "http://i.pga.com/pga/images/events/template_rev2/img/scoring/btn_add.gif";
				//change onClick Event
				myChildNodeA.onclick =
			    function() {
			     onClick=addRow(this.parentNode.parentNode.id);
			     return false;
			    }
				myChildNodeA.className = "";
				break;
		case "add_off":
				myChildNodeImg.src = "http://i.pga.com/pga/images/events/template_rev2/img/scoring/btn_add_off.gif";
				//change onClick Event
				myChildNodeA.onclick =
			    function() {
			     javascript:void(0);
			     return false;
			    }


				myChildNodeA.className = "disableCursor";
				break;
		default: newImageName = 'unknown';
	}
}

//Removes a row from myleaderboard
function removeRow(myRowId)
{
	if (window.event) {
		window.event.cancelBubble = true;
	}

	var the_row = document.getElementById(myRowId);  //id of the row that needs to be deleted
	var originalId = myRowId.substring(0,myRowId.indexOf("_2"));
	var theOriginalRow = document.getElementById(myRowId.substring(0,myRowId.indexOf("_2")));	//id of the original row that needs to be updated
	var myLeaderboardNode = document.getElementById('myLeaderboardBody');	//myLeaderboard table obj

	//Hide Table Break Body if MyLeaderboad doesn't contain any players
	if(myLeaderboardNode.getElementsByTagName("tr").length == 1)
	{
		hideTableBodies();
	}

	//remove id from cookie
	removeIdFromCookie(originalId);
	//remove row
	the_row.parentNode.removeChild(the_row);
	alternateRowColor(document.getElementById('myLeaderboardBody'));	//Make row color alternate
	//Change image and onclick event of the original row
	swapImage(theOriginalRow, "add");


}

// Write the cookie
function createCookie(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=/";
}


//Adds a player to cookie
function addPlayerToCookie(playerId)
{
		var currentPlayers = getCookie('cMyLeaderboard');		//gets current players from cookie
		var myPlayers;											//stores new player list

		if (currentPlayers) 									//if there are any current players and the new player to the end of the list and update the cookie
		{
			myPlayers = currentPlayers +","+ playerId;
			createCookie('cMyLeaderboard',myPlayers,7);
		}
		else
		{
			myPlayers = playerId;
			createCookie('cMyLeaderboard',myPlayers,7);
		}
}

//Gets cookies value and generates rows
function generateLeaderboardFromCookie()
{
	var myCurrentPlayers = getCookie('cMyLeaderboard');	//get cookie values
	if (myCurrentPlayers)		//if there are any players in the cookie, loop through them and add rows to myleaderboard table
	{
		var player = myCurrentPlayers.split(','); 				//parse string by comma

		for(var i=0;i < player.length;i++)
		{
			addRow(player[i], true);
		}
	}
	else
	{
		hideTableBodies();
	}
}

//Removes the playerId from the cookie that is passed to the function.
//Checks for 'playerid,' | ',playerid' | 'playerid' in cookie value and removes it.
function removeIdFromCookie(playerId)
{
	var myCurrentPlayers = getCookie('cMyLeaderboard');
	var playerC = playerId+",";	//player id with comma behind
	var cPlayer = ","+playerId;	//player id with comma in front
	var myPlayers;	//hold new value after playerid has been removed


	if (myCurrentPlayers.indexOf(playerC) >= 0){
		myPlayers = myCurrentPlayers.replace(playerC,"");}
	else if (myCurrentPlayers.indexOf(cPlayer) >= 0){
		myPlayers = myCurrentPlayers.replace(cPlayer,"");}
	else if (myCurrentPlayers.indexOf(playerId) >= 0){
		myPlayers = myCurrentPlayers.replace(playerId,"");}

	createCookie('cMyLeaderboard',myPlayers,7);		//created cookie with new values in it
}