<?php 
include_once 'connection.php';

#include 'html.php';

function standingsmall() {

#connection request 
$rightsidePDO = createDBH();
	
$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
$currentdivision = ( isset( $_GET['divid'] ) ) ?  $_GET['divid']  : NULL;
if ($currentteam != 0)
	{
		$seasonlevelFetch = $rightsidePDO->prepare('SELECT idSeason, idLevelSeason, Division FROM teamstatview WHERE idTeamAssignment = :teamid AND ((teamStartDate IS NULL OR CURDATE() > teamStartDate) AND (teamEndDate IS NULL OR CURDATE() < teamEndDate)) LIMIT 1');
		$seasonlevelFetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
		$seasonlevelFetch->execute();
		$seasonlevelFetched = $seasonlevelFetch->fetch(PDO::FETCH_ASSOC);
		$currentseason = $seasonlevelFetched['idSeason'];
		$currentlevel = $seasonlevelFetched['idLevelSeason'];
		$currentdivision = $seasonlevelFetched['Division'];
	}	
#Determines groupings by level and division, each detected level+division creates a standings group
	#Query to create list of possible subseasons per level
$standingsTableStart = 'SELECT DISTINCT idSeasonkey, subseason.SortOrder, level.SortPriority, idsubseasonkey, SubSeasonName, idLevelSeason, Level, TeamDivision FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey JOIN subseason ON teamstatassignment.idsubseasonkey = subseason.idsubseason JOIN level ON teamstatassignment.idLevelSeasonkey = level.idLevelSeason WHERE idSeasonkey = :seasonid AND idLevelSeason = :levelid';
if (!empty($currentdivision)) {$standingsTableStart .= ' AND TeamDivision = :teamdivision';}
if (!empty($currentteam)) {$standingsTableStart .= ' AND idTeamAssignment = :teamid';}
if (!empty($currentsubseason)) {$standingsTableStart .= ' AND idsubseasonkey = :subseasonid';}
$standingsTableStart .= ' GROUP BY idSeasonkey, subseason.SortOrder, level.SortPriority, TeamDivision ORDER BY idSeasonkey DESC, subseason.SortOrder DESC, level.SortPriority ASC, TeamDivision ASC';

$standingsFetchSQL = $rightsidePDO->prepare($standingsTableStart);	
$standingsFetchSQL->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
$standingsFetchSQL->bindParam(':levelid', $currentlevel, PDO::PARAM_INT);
if (!empty($currentdivision)) {$standingsFetchSQL->bindParam(':teamdivision', $currentdivision, PDO::PARAM_STR);}
if (!empty($currentteam)) {$standingsFetchSQL->bindParam(':teamid', $currentteam, PDO::PARAM_INT);}
if (!empty($currentsubseason)) {$standingsFetchSQL->bindParam(':subseasonid', $currentdivision, PDO::PARAM_INT);}
$standingsFetchSQL->execute();
$CombinationsCount = $standingsFetchSQL->rowCount();

#Sets variables for subseason div sections
$currentSubseason = '';
$currentSubseasonName = '';
$subseasoncontainer = '';
$currentrecord = 0;
#Takes each subseason/level/division grouping and creates standings table
while ($divisionrow = $standingsFetchSQL->fetch(PDO::FETCH_ASSOC))
	{
		$currentrecord++;
#Query 		
	#Gets playoff details at specified subseason/level
		$LevelPlayoffDetail = $rightsidePDO->prepare('SELECT DISTINCT idSeasonLevel, GamesRegularSeason, PlayoffsClinch, Playoffkey FROM SeasonLevels WHERE idSeason = :seasonid AND idLevel = :levelid AND idsubseasonkey = :subseasonid');
		$LevelPlayoffDetail->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
		$LevelPlayoffDetail->bindParam(':levelid', $divisionrow['idLevelSeason'], PDO::PARAM_INT);
		$LevelPlayoffDetail->bindParam(':subseasonid', $divisionrow['idsubseasonkey'], PDO::PARAM_INT);
		$LevelPlayoffDetail->execute();
		$LevelPlayoff = $LevelPlayoffDetail->fetch(PDO::FETCH_ASSOC);
		
		$levelcontainer = '<h1>'.$divisionrow['Level'].'</h1>';
		$divisionheader = '';
		$singlestandingtableHTML = '';
		$singleplayoffinfoHTML = '';
		$StandingsLevelLink = hockeyURLgenerator ($currentseason, $divisionrow['idLevelSeason'], $divisionrow['TeamDivision']);
		$divisionheader = '<h3><a href="index.php'.$StandingsLevelLink.'">'.$divisionrow['TeamDivision'].'</a></h3>';
			
		$StandingsSectionSQL = 'SELECT DISTINCT idTeamAssignment, TeamName, teamPrefix, TeamGamesPlayed, TeamWins, TeamLoss, TeamTie, TeamOTLoss, TeamPts, teamPlayoffMarker FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey JOIN team ON teamassignment.idTeamkey = team.idTeam JOIN season ON teamassignment.idSeasonkey = season.idSeason WHERE idSeason=:seasonid AND idsubseasonkey = :subseasonid AND idLevelSeasonkey = :levelid';
				
		if (!empty($divisionrow['TeamDivision']))
			{$StandingsSectionSQL .= ' AND TeamDivision LIKE :divisionid';}
		$StandingsSectionSQL .= ' AND ((teamstatassignment.teamStartDate IS NULL OR CURDATE() > teamstatassignment.teamStartDate) AND (teamstatassignment.teamEndDate is Null OR curdate() < teamstatassignment.teamEndDate)) ORDER BY TeamPts DESC, teamPlayoffMarker DESC, TeamWins DESC, TeamGamesPlayed ASC, teamPrefix';
		$StandingsFetch = $rightsidePDO->prepare($StandingsSectionSQL);
	
		$StandingsFetch->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
		$StandingsFetch->bindParam(':subseasonid', $divisionrow['idsubseasonkey'], PDO::PARAM_INT);
		$StandingsFetch->bindParam(':levelid', $divisionrow['idLevelSeason'], PDO::PARAM_INT);
		if (!empty($divisionrow['TeamDivision']))
			{$StandingsFetch->bindParam(':divisionid', $divisionrow['TeamDivision'], PDO::PARAM_STR); }

		
		$StandingsFetch->execute();
		
#Prepare Output for HTML
	#Adds Table id
		if (empty($divisionrow['TeamDivision'])) {$singlestandingtableHTML .= '<table>';}
		else {$singlestandingtableHTML .= '<h5><span id="standings-indent">'.$divisionrow['TeamDivision'].'</span></h5><table>';}
		
	#Adds table header (7 columns)
		$singlestandingtableHTML .= '<thead><tr><th>Team Name</th><th>GP</th><th>W</th><th>L</th><th>T</th><th>OTL</th><th>Pts</th></tr></thead><tbody>';

		$currentstanding = 0;
		$MagicNumber = 0;
		$gamesseason = $LevelPlayoff['GamesRegularSeason'];
		$TeamsPlayoffs = 0;
	#If there is a certain number advancing to the next round, adds a Magic Number
	while($Standingsrow = $StandingsFetch->fetch(PDO::FETCH_ASSOC)) {
	#Increases standing by 1 for every row
		$currentstanding++;
	#If a 'z - ' is detected in playoff marker, that team is not participating in a normal playoff and is excluded
		if ($Standingsrow['teamPlayoffMarker'] == 'z - ')
			{$currentstanding--;}
	#When the current standing goes beyond a playoff team the first time, a line is created spanning all 12 columns to delineate playoff/non-playoff
		if ($LevelPlayoff['PlayoffsClinch']+1 == $currentstanding AND $LevelPlayoff['PlayoffsClinch'] != 0) 
			{$singlestandingtableHTML .= '<tr><td colspan="12" class="playoffmarker"></td></tr>';}
	#When the current standing is beyond a playoff team, potential points is calculated for that team. The highest value from these teams is a Magic Number
		if ($LevelPlayoff['PlayoffsClinch']+1 <= $currentstanding) 
			{ $PotentialPoints = (($gamesseason - $Standingsrow['TeamGamesPlayed'])*2)+$Standingsrow['TeamPts'];
			if ($PotentialPoints > $MagicNumber)
				{$MagicNumber = $PotentialPoints;}
			}
	#Adds one for each team clinched for playoffs.  Used below to determine if a magic number is needed
		if ($Standingsrow['teamPlayoffMarker'] == 'x - ' || $Standingsrow['teamPlayoffMarker'] == 'y - ')
			{$TeamsPlayoffs++;}	
				
	#Outputs team table row for standings table
		$singlestandingtableHTML .= '<tr><td>'.$Standingsrow['teamPlayoffMarker'].'<a href="index.php?teamid='.$Standingsrow['idTeamAssignment'].'">';
		if (!empty($Standingsrow['teamPrefix'])) 
			{$singlestandingtableHTML .= $Standingsrow['teamPrefix'].' ';}
		$singlestandingtableHTML .= $Standingsrow['TeamName'].'</a></td><td>'.$Standingsrow['TeamGamesPlayed'].'</td><td>'.$Standingsrow['TeamWins'].'</td><td>'.$Standingsrow['TeamLoss'].'</td><td>'.$Standingsrow['TeamTie'].'</td><td>'.$Standingsrow['TeamOTLoss'].'</td><td>'.$Standingsrow['TeamPts'].'</td></tr>';
	}
	$singlestandingtableHTML .= '</tbody>';
	#If playoff key is filled, inserts playoff symbols into table footer
	if (!empty($subseasonrow['Playoffkey'])) 
		{$singlestandingtableHTML .= '<tfoot><tr><td colspan="7">'.$subseasonrow['Playoffkey'].'</td></tr></tfoot>';}
	$singlestandingtableHTML .= '</table><br />';
	/*Magic Number and info on who gets in is not included on the small version
#If in the regular season, add playoff information to column on the right
	#Adds Magic number if there are teams to clinch and not all teams are determined
	if ($subseasonrow['PlayoffsClinch'] > 0 AND $subseasonrow['idsubseasonkey'] == 1)
		{$singleplayoffinfoHTML .= 'Magic Number to Clinch Division Playoff Spot: '.$MagicNumber.'<br/><br/>';}
	#Adds playoff details if data is found in the table
	if (!empty($subseasonrow['PlayoffDetails']))
		{$singleplayoffinfoHTML .= $subseasonrow['PlayoffDetails'];}
	*/
	#Created Divs for standings on the left side and playoff and other info on the right
	$singleleveltableHTML = divBuilder('smallstandingstable','class',$singlestandingtableHTML);
	#echo $singleleveltableHTML;
	#This ifelse puts tables into subseason containers
	if ($CombinationsCount == $currentrecord) 
		{
			$currentsubseasonDiv = $singleleveltableHTML;
			if (empty($currentSubseasonName)) {$currentSubseasonName = $divisionrow['SubSeasonName'];}
			$subseasoncontainer .= divBuilder('smallsubseasonDiv','class','<h4>'.$currentSubseasonName.'</h4>'.$currentsubseasonDiv);
		}
	elseif (empty($currentsubseason)) 
		{
			$currentsubseason = $divisionrow['idsubseasonkey'];
			$currentsubseasonDiv = $singleleveltableHTML;
			$currentSubseasonName = $divisionrow['SubSeasonName'];
		}
	elseif ($currentsubseason == $divisionrow['idsubseasonkey']) 
		{
			$currentsubseasonDiv = $singleleveltableHTML;
		}
	elseif ($currentsubseason != $divisionrow['idsubseasonkey'])
		{
			$subseasoncontainer .= divBuilder('smallsubseasonDiv','class','<h4>'.$currentSubseasonName.'</h4>'.$currentsubseasonDiv);
			$currentSubseasonName = $divisionrow['SubSeasonName'];
			$currentsubseason = $divisionrow['idsubseasonkey'];
			$currentsubseasonDiv = $singleleveltableHTML;
		}
	else {echo 'Failure of elseif subseason section';}
	}
$standingsOutputHTML = divBuilder('smallstandingsdiv','class','<h1>Standings</h1>'.$subseasoncontainer);	

return $standingsOutputHTML;
}

function pastNews($newstarget, $newstargetid) {
	include '/home4/jjglover/games/GLSuserConnection.php';
	$pastNewsFetch = $rightsidePDO->prepare('SELECT NewsDate, NewsTitle, NewsItem, NewsAuthor, NewsAuthorLink FROM news JOIN newsdeliver ON news.idNews = newsdeliver.NewsidRef WHERE Target = :target AND Targetid = :targetid ORDER BY NewsDate LIMIT 5');
	$pastNewsFetch->bindParam(':target', $newstarget, PDO::PARAM_STR);
	$pastNewsFetch->bindParam(':targetid', $newstargetid, PDO::PARAM_STR);
	$pastNewsFetch->execute();
	$rightNewsFeed = '';
	while ($newsrow = $pastNewsFetch->fetch(PDO::FETCH_ASSOC))
	{
		$pastNewsItem = '<span class="rightNewsTitle">'.$newsrow['NewsTitle'].'</span>
		<span class="rightNewsAuthor">'.$newsrow['NewsDate'].' written by '.$newsrow['NewsAuthor'].'</span>';
		$rightNewsFeed .= divBuilder('rightNewsItem','class',$pastNewsItem);
	}
	$rightNewsSection = divBuilder('rightNewsSection','id',$rightNewsFeed);
return $rightNewsSection;
}

function pastResults($target, $targetdivision, $targetid) {
	if ($target == 'team')
	{
		$pastSQLWhere .= ' AND (HomeTeam = :idTeam or AwayTeam = :idTeam)';
	}
	elseif($target == 'division')
	{
		$pastSQLWhere .= ' AND hometeamassignment.idLevelSeason = :idLevel AND hometeamassignment.Division = :division';
	}
	elseif ($target == 'level')
	{
		$pastSQLWhere .= ' AND hometeamassignment.idLevelSeason = :idLevel';
	}
	elseif ($target == 'season')
	{
		$pastSQLWhere .= ' AND idSeasonkey = :idSeason';
	}
	$pastGamesSQLStart = 'SELECT DISTINCT idGame, GameDate, GameStartTime, LocationName, Rink, SubSeasonName, HomeTeam, hometeamassignment.TeamName as HomeTeamName, AwayTeam, awayteamassignment.TeamName as AwayTeamName, HomeGoals, AwayGoals FROM game JOIN teamstatview AS hometeamassignment ON game.HomeTeam = hometeamassignment.idTeamAssignment JOIN teamstatview AS awayteamassignment ON game.AwayTeam = awayteamassignment.idTeamAssignment JOIN location ON game.idLocationkey = location.idLocation JOIN subseason ON game.idsubseasonkey = subseason.idsubseason WHERE GameDate <= CURDATE() AND HomeShots > 0 AND AwayShots > 0 AND HomeGoals > 0 AND AwayGoals > 0';
	$pastGamesSQLEnd = ' ORDER BY GameDate DESC, GameStartTime DESC LIMIT 5';
	$PastGames = $rightsidePDO->prepare($pastGamesSQLStart.$pastSQLWhere.$pastGamesSQLEnd);

	if ($target == 'team')
	{
		$PastGames->bindParam(':idTeam', $targetid, PDO::PARAM_INT);
	}
	elseif ($target == 'division')
	{
		$PastGames->bindParam(':idLevel', $targetid, PDO::PARAM_INT);
		$PastGames->bindParam(':division', $targetdivision, PDO::PARAM_STR);
	}
	elseif ($target == 'level')
	{
		$PastGames->bindParam(':idLevel', $targetid, PDO::PARAM_INT);
	}
	elseif ($target == 'season')
	{
		$PastGames->bindParam(':idSeason', $targetid, PDO::PARAM_INT);
	}
	$PastGames->execute();
	
	while ($pastresults = $PastGames->fetch(PDO::FETCH_ASSOC))
	{
		#Create a new game item
		$SingleGame = '';
		$SingleGame .= '<span id="index-score">';
		
		if ($pastresults['AwayGoals'] > $pastresults['HomeGoals'])
			{$SingleGame .= '<b>'.$pastresults['AwayTeamName'].' '.$pastresults['AwayGoals'].'</b> - '.$pastresults['HomeTeamName'].' '.$pastresults['HomeGoals'];}
		elseif ($pastresults['AwayGoals'] < $pastresults['HomeGoals'])
			{$SingleGame .= $pastresults['AwayTeamName'].' '.$pastresults['AwayGoals'].' - <b>'.$pastresults['HomeTeamName'].' '.$pastresults['HomeGoals'].'</b>';}
		else
			{$SingleGame .= $pastresults['AwayTeamName'].' '.$pastresults['AwayGoals'].' - '.$pastresults['HomeTeamName'].' '.$pastresults['HomeGoals'];}
		
		$SingleGame .= '</span><br />';
		
		$SingleGame .= date("M j, Y", strtotime($pastresults['GameDate'])).' at '.date("g:i a", strtotime($pastresults['GameStartTime'])).' at '.$pastresults['LocationName'].' '.$pastresults['Rink'].'<br />';
		
		#Add Box score and any News
		$pastGameNewsFetch = 'SELECT idNews, NewsDate, NewsTitle, NewsItem, NewsAuthor, NewsAuthorLink, TeamAssignmentidAuthor FROM news JOIN newsdeliver ON news.idNews = newsdeliver.NewsidRef WHERE Target = "game" AND Targetid = :gameid';
		if ($currentteam != 0) {$pastGameNewsFetch .= ' AND TeamAssignmentidAuthor = :currentteam';}
		$SingleGame .= '<a href="gamerecap.php?gameid='.$pastresults['idGame'].'">Box Score</a>';
		$FetchRecap = $rightsidePDO->prepare($pastGameNewsFetch);
		#echo $pastGameNewsFetch;
		$FetchRecap->bindParam(':gameid', $pastresults['idGame'], PDO::PARAM_INT);
		if ($currentteam != 0) {$FetchRecap->bindParam(':currentteam', $currentteam, PDO::PARAM_INT);}
		$FetchRecap->execute();
		$CountRecaps = $FetchRecap->rowCount();
		if ($CountRecaps > 0)
		{
			while ($GameRecap = $FetchRecap->fetch(PDO::FETCH_ASSOC))
			{
				if ($pastresults['HomeTeam'] == $GameRecap['TeamAssignmentidAuthor'])
				{
					$HomeRecap = $pastresults['HomeTeamName'].' Recap: <a href="gamerecap.php?gameid='.$pastresults['idGame'].'&recap='.$GameRecap['TeamAssignmentidAuthor'].'">'.$GameRecap['NewsTitle'].'</a>';
				} else {$HomeRecap = '';}
				if ($pastresults['AwayTeam'] == $GameRecap['TeamAssignmentidAuthor'])
				{
					$AwayRecap = $pastresults['AwayTeamName'].' Recap: <a href="gamerecap.php?gameid='.$pastresults['idGame'].'&recap='.$GameRecap['TeamAssignmentidAuthor'].'">'.$GameRecap['NewsTitle'].'</a>';
				} else {$AwayRecap = '';}
				if ($pastresults['HomeTeam'] != $GameRecap['TeamAssignmentidAuthor'] && $pastresults['AwayTeam'] != $GameRecap['TeamAssignmentidAuthor'])
				{$OtherRecap = $GameRecap['NewsTitle'];}
			}
			$RecapClass = divBuilder('gamerecap','class', $HomeRecap.$AwayRecap.$OtherRecap);
			$SingleGame .= $RecapClass;
		}
		$RecentGameList .= divBuilder('singlegameitem','class',$SingleGame);
	}
	$rightGameDiv = divBuilder('rightgamediv','id',$RecentGameList);
	return $rightGameDiv;	
}
/*
function twitterEmbed($twitterid) {
	$Twittercode = '<a class="twitter-timeline" data-height="500" href="https://twitter.com/'.$twitterid.'">Tweets by Goallinestats</a> <script async src="//platform.twitter.com/widgets.js"charset="utf-8"></script>';
	
return $Twittercode;
}
*/
function getTwitterID() {
	$setNDBH = createNDBH();	
	$setDBH = createDBH();
	$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
	$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
	$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
	$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
	$currentdivision = ( isset( $_GET['divid'] ) ) ?  $_GET['divid']  : NULL;
	
	if ($currentteam != 0) {
		$findTeamKey = $setDBH->prepare('SELECT idTeamkey FROM teamassignment WHERE idTeamAssignment = :idTeam LIMIT 1');	
		$findTeamKey->bindParam(':idTeam', $currentteam, PDO::PARAM_INT);
		$findTeamKey->execute();
		$foundTeamKey = $findTeamKey->fetch(PDO::FETCH_ASSOC);
		
		$fetchTwitter = $setNDBH->prepare('SELECT TwitterURL FROM socialteam WHERE idTeamkeyRef = :idTeam AND twitterActive = 1 LIMIT 1');
		$fetchTwitter->bindParam(':idTeam', $foundTeamKey['idTeamkey'], PDO::PARAM_INT);
		$fetchTwitter->execute();
		$countRecord = $fetchTwitter->rowCount();
		if ($countRecord > 0) {
			$foundTwitter = $fetchTwitter->fetch(PDO::FETCH_ASSOC);
			return $foundTwitter['TwitterURL'];
		}
	} 
}

function createSearch() {
	$searchCode = 'Search by last name or team:<br />
	<input type="text" id="searchbox">
	<input type="button" value="Search" onclick="startsearch()">';
	$searchDiv = divBuilder('searchDiv','id',$searchCode);
	$retriveDiv = divBuilder('retrieveDiv','id','');
	
return '<h1>Search:</h1>'.$searchDiv.$retriveDiv;
}

function searchEngine($searchitem) {
	#include '/home4/jjglover/games/GLSuserConnection.php';
	#include_once '/home4/jjglover/games/html.php';	
	$rightsidePDO = createDBH();
	$searchitem = '%'.$searchitem.'%';

	$searchPlayer = "SELECT idPlayers, PlayerLast, PlayerFirst FROM players WHERE PlayerLast LIKE :name OR PlayerFirst = :name LIMIT 10";
		
	$searchPlayerSQL = $rightsidePDO->prepare($searchPlayer);
	$searchPlayerSQL->bindParam(':name', $searchitem, PDO::PARAM_STR);
	$searchPlayerSQL->execute();
	
	$searchTeam = "SELECT idTeamAssignment, TeamName, SeasonDisplay FROM team JOIN teamassignment ON team.idTeam = teamassignment.idTeamkey JOIN season ON teamassignment.idSeasonkey = season.idSeason WHERE TeamName LIKE :name ORDER BY season.SeasonStart DESC LIMIT 10";
	
	$searchTeamSQL = $rightsidePDO->prepare($searchTeam);
	$searchTeamSQL->bindParam(':name', $searchitem, PDO::PARAM_STR);
	$searchTeamSQL->execute();
	
	$foundPlayerSQL = $searchPlayerSQL->rowCount();
	$foundTeamSQL = $searchTeamSQL->rowCount();
	$playerResults = [];
	$teamResults = [];	
	if ($foundPlayerSQL > 0) {
		while ($foundPlayers = $searchPlayerSQL->fetch(PDO::FETCH_ASSOC)) {
			$playerResults[] = ['link' => 'playercard?playerid='.$foundPlayers['idPlayers'], 'display' => $foundPlayers['PlayerLast'].', '.$foundPlayers['PlayerFirst']];
		}
	}

	if ($foundTeamSQL > 0) {
		while ($foundTeam = $searchTeamSQL->fetch(PDO::FETCH_ASSOC)) {
			#$returnTeam .= '<a href="index.php?teamid='.$foundTeam['idTeamAssignment'].'">'.$foundTeam['TeamName'].' - '.$foundTeam['SeasonDisplay'].'</a><br />';
			$teamResults[] = ['link' => 'index?teamid='.$foundTeam['idTeamAssignment'], 'display' => $foundTeam['TeamName'].' - '.$foundTeam['SeasonDisplay']];
		}
	}
	$returnSearch = [
		'playerResults' => $playerResults,
		'teamResults'=> $teamResults
	];

echo json_encode($returnSearch);
}
$AJAXstep = isset($_POST['step']) ? $_POST['step'] : '';

if ($AJAXstep == 'search') {
	$searchterm = $_POST['searchphrase'];
	searchEngine($searchterm);
}

function JSONstandingsmall() {

	#connection request 
	$rightsidePDO = createDBH();
		
	$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
	$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
	$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
	$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
	$currentdivision = ( isset( $_GET['divid'] ) ) ?  $_GET['divid']  : NULL;

	if ($currentteam != 0)
		{
			$seasonlevelFetch = $rightsidePDO->prepare('SELECT idSeason, idLevelSeason, Division FROM teamstatview WHERE idTeamAssignment = :teamid  AND ((teamStartDate IS NULL OR CURDATE() > teamStartDate) AND (teamEndDate IS NULL OR CURDATE() < teamEndDate)) LIMIT 1');
			$seasonlevelFetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
			$seasonlevelFetch->execute();
			$seasonlevelFetched = $seasonlevelFetch->fetch(PDO::FETCH_ASSOC);
			$currentseason = $seasonlevelFetched['idSeason'];
			$currentlevel = $seasonlevelFetched['idLevelSeason'];
			$currentdivision = $seasonlevelFetched['Division'];
		}	

	#Determines groupings by level and division, each detected level+division creates a standings group
		#Query to create list of possible subseasons per level
		$standingsTableStart = 'SELECT DISTINCT idSeasonkey, idsubseasonkey, SubSeasonName, subseason.SortOrder, level.SortPriority, idLevelSeason, Level, TeamDivision FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey JOIN subseason ON teamstatassignment.idsubseasonkey = subseason.idsubseason JOIN level ON teamstatassignment.idLevelSeasonkey = level.idLevelSeason WHERE idSeasonkey = :seasonid AND idLevelSeason = :levelid';
		if (!empty($currentdivision)) {$standingsTableStart .= ' AND TeamDivision = :teamdivision';}
		if (!empty($currentteam)) {$standingsTableStart .= ' AND idTeamAssignment = :teamid';}
		if (!empty($currentsubseason)) {$standingsTableStart .= ' AND idsubseasonkey = :subseasonid';}
		$standingsTableStart .= ' AND ((teamstatassignment.teamStartDate IS NULL OR CURDATE() > teamstatassignment.teamStartDate) AND (teamstatassignment.teamEndDate IS NULL OR CURDATE() < teamstatassignment.teamEndDate)) ORDER BY idSeasonkey DESC, subseason.SortOrder DESC, level.SortPriority ASC, TeamDivision ASC';

	$standingsFetchSQL = $rightsidePDO->prepare($standingsTableStart);	
	$standingsFetchSQL->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
	$standingsFetchSQL->bindParam(':levelid', $currentlevel, PDO::PARAM_INT);
	if (!empty($currentdivision)) {$standingsFetchSQL->bindParam(':teamdivision', $currentdivision, PDO::PARAM_STR);}
	if (!empty($currentteam)) {$standingsFetchSQL->bindParam(':teamid', $currentteam, PDO::PARAM_INT);}
	if (!empty($currentsubseason)) {$standingsFetchSQL->bindParam(':subseasonid', $currentdivision, PDO::PARAM_INT);}

	$standingsFetchSQL->execute();
	$CombinationsCount = $standingsFetchSQL->rowCount();
	
	#Sets variables for subseason div sections
	$currentSubseason = '';
	$currentSubseasonName = '';
	$subseasoncontainer = '';
	$currentrecord = 0;
	$JSONOutput = array();
	$fullDataArray = array();
	#Takes each subseason/level/division grouping and creates standings table
	while ($divisionrow = $standingsFetchSQL->fetch(PDO::FETCH_ASSOC))
		{
			$currentrecord++;
	#Query 		
		#Gets playoff details at specified subseason/level
			$LevelPlayoffDetail = $rightsidePDO->prepare('SELECT DISTINCT idSeasonLevel, GamesRegularSeason, PlayoffsClinch, Playoffkey FROM SeasonLevels WHERE idSeason = :seasonid AND idLevel = :levelid AND idsubseasonkey = :subseasonid');
			$LevelPlayoffDetail->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
			$LevelPlayoffDetail->bindParam(':levelid', $divisionrow['idLevelSeason'], PDO::PARAM_INT);
			$LevelPlayoffDetail->bindParam(':subseasonid', $divisionrow['idsubseasonkey'], PDO::PARAM_INT);
			$LevelPlayoffDetail->execute();
			$LevelPlayoff = $LevelPlayoffDetail->fetch(PDO::FETCH_ASSOC);
			
			$levelcontainer = '<h1>'.$divisionrow['Level'].'</h1>';
			$divisionheader = '';
			$singlestandingtableHTML = '';
			$singleplayoffinfoHTML = '';
			#$StandingsLevelLink = hockeyURLgenerator ($currentseason, $divisionrow['idLevelSeason'], $divisionrow['TeamDivision']);
			#$divisionheader = '<h3><a href="index.php'.$StandingsLevelLink.'">'.$divisionrow['TeamDivision'].'</a></h3>';
			$JSONOutput += ['header'=> (array('title'=> $divisionrow['Level']))];
			if (!empty($divisionrow['TeamDivision'])) {
				$JSONOutput += ['subheader'=> (array('title'=> $divisionrow['TeamDivision'], 'link'=>null))];
			} 
				
			$StandingsSectionSQL = 'SELECT DISTINCT idTeamAssignment, TeamName, teamPrefix, TeamGamesPlayed, TeamWins, TeamLoss, TeamTie, TeamOTLoss, TeamPts, teamPlayoffMarker, cssCustom FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey LEFT JOIN jjglover_GLSHockey_NewsCss.cssteamassignment ON idTeamAssignmentkey = cssteamassignment.TeamidRef AND jjglover_GLSHockey_NewsCss.cssteamassignment.TeamtableRef = "teamassignment" JOIN team ON teamassignment.idTeamkey = team.idTeam JOIN season ON teamassignment.idSeasonkey = season.idSeason WHERE idSeason=:seasonid AND idsubseasonkey = :subseasonid AND idLevelSeasonkey = :levelid';
					
			if (!empty($divisionrow['TeamDivision']))
				{$StandingsSectionSQL .= ' AND TeamDivision LIKE :divisionid';}
			$StandingsSectionSQL .= ' AND ((teamstatassignment.teamStartDate IS NULL OR CURDATE() > teamstatassignment.teamStartDate) AND (teamstatassignment.teamEndDate is Null OR curdate() < teamstatassignment.teamEndDate))  ORDER BY TeamPts DESC, teamPlayoffMarker DESC, TeamWins DESC, TeamGamesPlayed ASC, teamPrefix';
			$StandingsFetch = $rightsidePDO->prepare($StandingsSectionSQL);
			$StandingsFetch->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
			$StandingsFetch->bindParam(':subseasonid', $divisionrow['idsubseasonkey'], PDO::PARAM_INT);
			$StandingsFetch->bindParam(':levelid', $divisionrow['idLevelSeason'], PDO::PARAM_INT);
			if (!empty($divisionrow['TeamDivision']))
				{$StandingsFetch->bindParam(':divisionid', $divisionrow['TeamDivision'], PDO::PARAM_STR); }

			
			$StandingsFetch->execute();

	#Prepare Output for HTML
		#Adds Table id
			if (empty($divisionrow['TeamDivision'])) {$singlestandingtableHTML .= '<table>';}
			else {$singlestandingtableHTML .= '<h5><span id="standings-indent">'.$divisionrow['TeamDivision'].'</span></h5><table>';}
			
		#Adds table header (7 columns)	
			$currentstanding = 0;
			$MagicNumber = 0;
			$gamesseason = $LevelPlayoff['GamesRegularSeason'];
			$TeamsPlayoffs = 0;
		#If there is a certain number advancing to the next round, adds a Magic Number
		
		$tableArray = array();
		while($Standingsrow = $StandingsFetch->fetch(PDO::FETCH_ASSOC)) {
			
		#Increases standing by 1 for every row
			$currentstanding++;
		#If a 'z - ' is detected in playoff marker, that team is not participating in a normal playoff and is excluded
			if ($Standingsrow['teamPlayoffMarker'] == 'z - ')
				{$currentstanding--;}
		#When the current standing goes beyond a playoff team the first time, a line is created spanning all 12 columns to delineate playoff/non-playoff
			if ($LevelPlayoff['PlayoffsClinch']+1 == $currentstanding AND $LevelPlayoff['PlayoffsClinch'] != 0) 
				{$singlestandingtableHTML .= '<tr><td colspan="12" class="playoffmarker"></td></tr>';}
		#When the current standing is beyond a playoff team, potential points is calculated for that team. The highest value from these teams is a Magic Number
			if ($LevelPlayoff['PlayoffsClinch']+1 <= $currentstanding) 
				{ $PotentialPoints = (($gamesseason - $Standingsrow['TeamGamesPlayed'])*2)+$Standingsrow['TeamPts'];
				if ($PotentialPoints > $MagicNumber)
					{$MagicNumber = $PotentialPoints;}
				}
		#Adds one for each team clinched for playoffs.  Used below to determine if a magic number is needed
			if ($Standingsrow['teamPlayoffMarker'] == 'x - ' || $Standingsrow['teamPlayoffMarker'] == 'y - ')
				{$TeamsPlayoffs++;}	
					
		#Outputs team table row for standings table
			$teamName = $Standingsrow['TeamName'];
			//if (!empty($Standingsrow['cssCustom'])) {$cssTheme = $Standingsrow['cssCustom'];} else {$cssTheme = '';}
			$cssTheme = '';
			if (!empty($Standingsrow['teamPlayoffMarker']))
				{$teamName = $Standingsrow['teamPlayoffMarker'].' '.$teamName;}
			if (!empty($Standingsrow['teamPrefix'])) 
				{$teamName = '('.$Standingsrow['teamPrefix'].') '.$teamName;}

			$tableArray[] = array('idTeamAssignment'=> $Standingsrow['idTeamAssignment'], 'Team' => $teamName, 'TeamTheme' => $cssTheme, 'G' => $Standingsrow['TeamGamesPlayed'], 'W' => $Standingsrow['TeamWins'], 'L' => $Standingsrow['TeamLoss'], 'T' => $Standingsrow['TeamTie'], 'OTL' => $Standingsrow['TeamOTLoss'], 'Pts' => $Standingsrow['TeamPts']);
		}

		#If playoff key is filled, inserts playoff symbols into table footer
		if (!empty($subseasonrow['Playoffkey'])) 
			{$singlestandingtableHTML .= '<tfoot><tr><td colspan="7">'.$subseasonrow['Playoffkey'].'</td></tr></tfoot>';}
		$singlestandingtableHTML .= '</table><br />';
		/*Magic Number and info on who gets in is not included on the small version
	#If in the regular season, add playoff information to column on the right
		#Adds Magic number if there are teams to clinch and not all teams are determined
		if ($subseasonrow['PlayoffsClinch'] > 0 AND $subseasonrow['idsubseasonkey'] == 1)
			{$singleplayoffinfoHTML .= 'Magic Number to Clinch Division Playoff Spot: '.$MagicNumber.'<br/><br/>';}
		#Adds playoff details if data is found in the table
		if (!empty($subseasonrow['PlayoffDetails']))
			{$singleplayoffinfoHTML .= $subseasonrow['PlayoffDetails'];}
		
		#Created Divs for standings on the left side and playoff and other info on the right
		$singleleveltableHTML = divBuilder('smallstandingstable','class',$singlestandingtableHTML);
		#echo $singleleveltableHTML;
		#This ifelse puts tables into subseason containers
		if ($CombinationsCount == $currentrecord) 
			{
				$currentsubseasonDiv = $singleleveltableHTML;
				if (empty($currentSubseasonName)) {$currentSubseasonName = $divisionrow['SubSeasonName'];}
				$subseasoncontainer .= divBuilder('smallsubseasonDiv','class','<h4>'.$currentSubseasonName.'</h4>'.$currentsubseasonDiv);
			}
		elseif (empty($currentsubseason)) 
			{
				$currentsubseason = $divisionrow['idsubseasonkey'];
				$currentsubseasonDiv = $singleleveltableHTML;
				$currentSubseasonName = $divisionrow['SubSeasonName'];
			}
		elseif ($currentsubseason == $divisionrow['idsubseasonkey']) 
			{
				$currentsubseasonDiv = $singleleveltableHTML;
			}
		elseif ($currentsubseason != $divisionrow['idsubseasonkey'])
			{
				$subseasoncontainer .= divBuilder('smallsubseasonDiv','class','<h4>'.$currentSubseasonName.'</h4>'.$currentsubseasonDiv);
				$currentSubseasonName = $divisionrow['SubSeasonName'];
				$currentsubseason = $divisionrow['idsubseasonkey'];
				$currentsubseasonDiv = $singleleveltableHTML;
			}
		else {echo 'Failure of elseif subseason section';}
*/
			$tableHeader = $divisionrow['SubSeasonName'];
			if (!empty($divisionrow['TeamDivision'])) {$tableHeader .= ' - '.$divisionrow['TeamDivision'];}

		$JSONDataOutput = array(
			'dataarray' => $tableArray,
			'tableid' => '',
			'tableclass' => 'smallstandingstable tablesorter',
			'tablesort' => null,
			'linkslist' => array(array('link'=>'team?teamid=','linktarget'=>'idTeamAssignment','linkname'=>'Team')),
			'imagelist' => ''
		);
		$JSONDataOutput += ['cardHeader' => $tableHeader];
		$fullDataArray[] = $JSONDataOutput;
	}
	$JSONOutput += ['tables' => $fullDataArray];	
	#$standingsOutputHTML = divBuilder('smallstandingsdiv','class','<h1>Standings</h1>'.$subseasoncontainer);	
	return $JSONOutput;
	#return $standingsOutputHTML;
	}

$step = $_GET['step'];	
switch ($step) {
	case 0:
		$fetchStandings = JSONstandingsmall();
		echo json_encode($fetchStandings);
	break;
	case 1:
		echo getTwitterID();
	break;
	case 2:
		$runSearch = searchEngine($searchitem);
	break;
	case 3:
		$searchitem = $_GET['search'];
		searchEngine($searchitem);
	break;
	default: echo 'error in Step for RightsideWidgets';
}

?>