<?php defined( '_BIGNIGHT_EXEC' ) or die( 'Restricted access' );?>

	<a href="index.php?view=user">&lt;&lt; back to profile</a>
	<p>Select avatar:</p>
	<form id="avatars" name="avatars" method="post" action="index.php?view=avatar">
<?php
	global $error;
	global $user;
	
	if($user===NULL){
		die ("Error! You are not logged on.");
	}
	
	$handler = opendir("images/avatars/");
	$avatars = array();
    while ($file = readdir($handler))
		if ($file != "." && $file != ".." && $file != "1.jpg")
			if(preg_match("/^([0-9]+).jpg$/",$file,$array))
				$avatars[] = $array[1];
	
	$col=1;
	
	if(isset($_POST["avatar"])){
		$new_avatar = intval($_POST["avatar"]);
		if($new_avatar==1 || in_array($new_avatar,$avatars)){
			global $DB;
			$DB->qry("UPDATE users SET avatar={$new_avatar} WHERE username='{$user["username"]}';");
			$user["avatar"]=$new_avatar;
		} else {
			$error .= "Error changing avatar. ";
		}
	}
	
	if(count($avatars)==0) $error .= "Error! No avatars found. ";
	else {
		sort($avatars);
		echo "<table class=\"avatars\">\n<tr>\n";
		foreach($avatars as $i){
			if($col>5) {
				echo "</tr><tr>";
				$col = 1;
			}
			
			echo "<td><label><span><img src=\"images/avatars/{$i}.jpg\"></span><input type=\"radio\" name=\"avatar\" value=\"{$i}\" ";
			if($user["avatar"]==$i) echo "checked";
			else echo "onchange=\"document.avatars.submit();\"";
			echo " ></label></td>";
			$col++;
		}
		while($col<=5){
			echo "<td style=\"border:0px\"></td>";
			$col++;
		}
		echo "<tr><td colspan=\"5\" style=\"border:0px\">";
		echo "<label>No avatar</span><input type=\"radio\" name=\"avatar\" value=\"1\" ";
		if($user["avatar"]==1) echo "checked";
		else echo "onchange=\"document.avatars.submit();\"";
		echo " ></label>";
		echo "</td></tr>\n";
		echo "<tr><td colspan=\"5\" style=\"border:0px\">";
		echo "<input type=\"submit\" name=\"avatar-submit\" value=\"Save Changes\"> <a href=\"index.php?view=user\">Return</a>";
		echo "</td></tr></table>\n";
		
		
	}
?>
	
	</form>
	<a href="index.php?view=user">&lt;&lt; back to profile</a>