<?

////////////////////////////////
$EnforceSession = true;
include "includes/includes.php";
////////////////////////////////
	

// Make sure it carries on
$displayMySqlErrors = 1;
$RowMod = 4;
$PageDisplayCount = 12;
$StartIndex = 0;

if( request("StartIndex") != "" ) $StartIndex = intval(request("StartIndex"));

$WhereQuery = "site = '" . $gblSiteName . "'";
$query = "SELECT * FROM puzzles WHERE site = '" . $gblSiteName . "' AND number <= " . $UnlockedPuzzles . " ORDER BY number LIMIT " . $StartIndex . ", " . $PageDisplayCount;

$PuzzleCount = $UnlockedPuzzles;
if( $PuzzleCount > $StartIndex + 1 + $PageDisplayCount )
	$EndIndex = $StartIndex + $PageDisplayCount;
else
	$EndIndex = $PuzzleCount;

// Header
include "includes/header.php";

// Begin Template
$tp = new PhpTemplate;
for( $tp->StartFromFile("templates/puzzles.template" ); $tp->NextAndEchoOutput(); ) {

	CheckGlobalEscapes($tp);

	if( $tp->IsEscape("ROWMOD") ) $RowMod = intval(trim($tp->GetEscapeArgument()));
	else if( $tp->IsEscape("START-INDEX") ) echo $StartIndex + 1;
	else if( $tp->IsEscape("END-INDEX") ) echo $EndIndex;
	else if( $tp->IsEscape("RESULT-COUNT") ) echo $PuzzleCount;
	else if( $tp->IsEscape("IF-PREV") )
	{
		if( $StartIndex > 0 )
			$tp->PushArgumentToStream();
	}
	else if( $tp->IsEscape("IF-NEXT") )
	{
		if( $PuzzleCount > $EndIndex )
			$tp->PushArgumentToStream();
	}
	else if( $tp->IsEscape("PREVSTART") ) echo $StartIndex - $PageDisplayCount;
	else if( $tp->IsEscape("NEXTSTART") ) echo $StartIndex + $PageDisplayCount;	
	else if( $tp->IsEscape("IF-ARE-NOT-PUZZLES") )
	{
		if( $PuzzleCount == 0 )
			$tp->PushArgumentToStream();
	}
	else if( $tp->IsEscape("IF-ARE-PUZZLES") )	
	{
		if( $PuzzleCount > 0 )
			$tp->PushArgumentToStream();	
	}	
	else if( $tp->IsEscape("PUZZLES") )
	{

		// Connect
		$db = mysql_connect("localhost", $gblMySqlUser, $gblMySqlPass);
		mysql_select_db($gblMySqlDb, $db);

		// Retrieve data
		$result = mysql_query($query, $db);

		// Loop results
		for( $RowIndex = 0; $a = mysql_fetch_array($result); $RowIndex++ )
		{
			$Record = new PhpSqlRow;
			$Record->SetAsArray($a);

			$tpElem = new PhpTemplate;						
			for( $tpElem->Start( $tp->GetEscapeArgument() ); $tpElem->NextAndEchoOutput(); ) 
			{

				CheckGlobalEscapes($tpElem);

				if( $tpElem->IsEscape("IF-NEW-ROW") )
				{
					if( ($RowIndex + 1) % $RowMod == 0 )
						echo $tpElem->GetEscapeArgument();
				}
				else if( $tpElem->IsEscape("INDEX") ) echo $RowIndex;
				else if( $tpElem->IsEscape("ID") ) echo $Record->GetValue("id");
				else if( $tpElem->IsEscape("TYPE") ) echo $Record->GetValue("puzzletype");
			}

		}			

	}
}

// Footer
include "includes/footer.php";

?>