<?
// Include Access Class and start/resume session (unless logging out)
if ($_GET['cmd'] != "logout") {
	include ('includes/access_user_class.php');
	include ('includes/access_user_extn.php');
	$my_access = new ETHAccessUser(false);
}

// include the MySql DB config and functions
include_once 'includes/config.php';
//if ($_SESSION['user'] == "Woody") {
//	include_once 'includes/functions1.php';
//} else {
	include_once 'includes/functions.php';
//}
include_once 'includes/sb_functions.php';
include_once 'includes/access_functions.php';
include_once 'includes/split_result.php';
include_once 'includes/geoip.inc';
$gi = geoip_open('includes/GeoIP.dat', GEOIP_STANDARD);

// Open Database connection
$db_link = mysql_connect($server, $db_user, $db_pass) or die ("MySQL Database CONNECT Error");
mysql_select_db($db, $db_link) or die ("MySQL Database SELECT Error");
mysql_query("SET NAMES 'utf8'");

// Initialise Main Variables
$secs_remaining = 0;
$t_started = $reset_count = $last_reset_by = $last_reset_ip = 0;
$t_max = 108*60;
$t_failure = 40;
$ajax_response = null;
$ip_address = $_SERVER['REMOTE_ADDR'];
$referer = $_SERVER['HTTP_REFERER'];
$reservation_credits = reserve_credits();


// Find out status of clock timer
$result = mysql_query("SELECT * FROM timer ORDER BY timer_id DESC LIMIT 1", $db_link) or die("Database LOOKUP Error");
if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	$timer_id = $row["timer_id"];
	$t_started = $row["timer_started"];
	$running_since = $row["running_since"];
	$reset_count = $row["reset_count"];
	$failsafe_count = $row["failsafe_count"];
	$chat_active = $row["chat_active"];
	$last_reset_by = $row["last_reset_by"];
	$last_reset_ip = $row["last_reset_ip"];
}


// Access / Screen Name Functions
access_process();
$_SESSION['nickname'] = (isset($_SESSION['user'])) ? $_SESSION['user'] : null;
if (isset($_SESSION['logged_in'])) {
	$my_access->get_user_info();
	$_SESSION['login_id'] = $my_access->id;
	
	// Logout any blocked users
	if ( !$my_access->check_user() ) $my_access->log_out(); 
}

// Set a cookie to make sure it's not a bot
if (!$_SESSION['dharma']) {
	$_SESSION['dharma'] = $_COOKIE['dharma'] = md5(uniqid(rand(), TRUE));
	setcookie("dharma",$_SESSION['dharma'],0,"/",".enterthehatch.com");
	mysql_query("UPDATE users SET dharma_cookie = '".$_SESSION['dharma']."' WHERE login = ".quote_smart($_SESSION['user'])." LIMIT 1", $db_link) or die("Dharma: UPDATE Error");
}

// Get number of secs remaining
$t_now = time();
$secs_remaining = $t_max - ($t_now - $t_started);

// Update ignore lists
ignore_update();

// Reset timer after System Failure (new visitors only)
if ($t_started < $t_now - ($t_max + $t_failure) && !$_GET['q'] && !$_POST['cmd']) {

	mysql_query("INSERT INTO timer (id, timer_id, timer_started, running_since, reset_count, failsafe_count, last_reset_ip, last_reset_by) VALUES (NULL, ".($timer_id+1).", $t_now, $t_now, '0', '0', 'n/a', 'n/a')", $db_link) or die("Clock: RESET Error");
	mysql_query("UPDATE stats SET value = value + 1 WHERE name = 'failure_count'", $db_link) or die("New Timer: Stats UPDATE Error");

	$t_stop = $t_started + $t_max + $t_failure;

	// Did we break the reset record? If so, update most resets time
	$mrt_result = mysql_query("SELECT value FROM stats WHERE name = 'most_resets_time'", $db_link) or die("New Timer: Stats LOOKUP Error");
	$mrt_row = mysql_fetch_array($mrt_result, MYSQL_ASSOC);
	if ($mrt_row['value'] < ($t_stop-$running_since)) {
		mysql_query("UPDATE stats SET value = $t_stop-$running_since WHERE name = 'most_resets_time'", $db_link) or die("New Timer: Stats UPDATE Error");
	}
	
	// Update Timer History
	$reset_by = (isset($_SESSION['nickname']))? $_SESSION['nickname'] : 'n/a';
	mysql_query("INSERT INTO history (timer_id, timestamp, ip, name, action) VALUES ('$timer_id','$t_stop','n/a','n/a','System Failure')", $db_link) or die("History: INSERT Error");
	$timer_id += 1;
	mysql_query("INSERT INTO history (timer_id, timestamp, ip, name, action) VALUES ('$timer_id','$t_now','$ip_address', ".quote_smart($reset_by).",'Timer Started')", $db_link) or die("History: INSERT Error");
	
	// Reset hatch and delete chat
	$secs_remaining = $t_max;
	shoutboxDelete();
	
	// Delete personal reset tracking
	mysql_query("UPDATE users SET solo_lastreset = '0', solo_score = '0' WHERE 1", $db_link) or die("Solo Resets: UPDATE Error");
	
	
	// Send a notification of system failure
	$headers = "From: Enter The Hatch <contact@enterthehatch.com>\r\n" .
				"Reply-To: contact@enterthehatch.com\r\n" .
				"X-Mailer: enterthehatch.com\r\n";
	mail("martin.s.fisher@gmail.com", "***ETH*** - System Failure Notification", "The timer failed and was restarted just now by $reset_by ($ip_address).", $headers);

}

// Output Headers: No cache and Date in past to ensure fresh response each time
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


// Check for AJAX Requests
if ($_REQUEST['q']) {
	$ajax_response = null;

/*	// Make sure request is coming from site
	if (check_not_null($referer) == false || !strpos($referer, "enterthehatch.com") ) {
		whos_online("invalid");
		$ajax_response = 'invalid';	
	} else ...
*/

	switch ($_GET['q']) {
	case "secs":
		// Timer *Update*
		if ($_SESSION['lockedinarmoury'])
			whos_online("armoury");
		else
			whos_online("timesync");
		$ajax_response = $secs_remaining;
		break;

	case "reset":
		$who = (isset($_SESSION['nickname']))?$_SESSION['nickname']:'A guest';

		// Reset only allowed at 4 mins or less
		if ($secs_remaining <= 240 && isset($_GET['sid'])) {
		
			// Look out for cheaters
			if (!isset($_SESSION['last_reset_sid'])) {
				// Log the reset sid time in session
				$_SESSION['last_reset_sid'] = $_GET['sid'];
			
			} else if ($_GET['sid'] - $_SESSION['last_reset_sid'] <= 1) {
				// something fishy... (reset request less than 2 seconds apart)
				if (isset($_SESSION['user']) && isset($_SESSION['logged_in'])) {
					$message = "--- Warning: anomaly detected. $who has been logged out ---";
					sys_msg('Dharma Admin', $message);
					$my_access->log_out();
				} else {
					// Not logged in so slow roll them
					$_SESSION['dharma'] = md5(uniqid(rand(), TRUE));;	
				}
				whos_online("anomaly");
				break;
			}

			// Keyboard is not activated until 239 seconds - so 240 has to be cheating
			if ($secs_remaining == 240) {
				whos_online("kilcheat");
				if (isset($_SESSION['user']) && isset($_SESSION['logged_in'])) {
					$message = "--- $who tried to cheat and their account was terminated ---";
					sys_msg('Dharma Admin', $message);
				}
				block_cheater();
				break;
			}
			
			// Check user is not locked in armoury this reset
			if (check_armoury() == true && $secs_remaining > 60) {
				whos_online("rsetarmy");
				sys_msg($who, "--- $who tried to push the button, but is currently locked in the armoury ---");
				solo_score($reset_count+1);
				access_upgrade();
				$ajax_response = 'reset_armoury';
			
			// Slow roll bots and cheating guests ...
			//} else if ($_SESSION['dharma'] != $_COOKIE['dharma'] && $secs_remaining >= 235) {
			//	sleep(3);
				//$t_now = time();
				//$secs_remaining = $t_max - ($t_now - $t_started);
				//whos_online("rsetfail");
				//sys_msg($who, "--- $who tried to push the button, but was beaten to it. ---");
				//$ajax_response = $secs_remaining;
			
			
			// Successful reset!
			} else if (!reservation_check() || $secs_remaining <= 3*60) {
				// Update Whois Online last click and reset stats
				whos_online("reset_ok");
				reset_timer();
				access_upgrade();
				$ajax_response = 'reset_ok';

			// Timer was reserved
			} else {
				whos_online("rsetblok");
				sys_msg($who, "--- $who tried to push the button, but it was reserved ---");
				solo_score($reset_count+1);
				access_upgrade();
				$ajax_response = 'reset_blocked';
			}

		// Timer was already reset by someone else (allows 280s as solo players can PTB until end of system failure sequence)
		} else if ($secs_remaining >= 6200 && isset($_GET['sid'])) {
			whos_online("rsetfail");
			sys_msg($who, "--- $who tried to push the button, but was beaten to it ---");
			solo_score($reset_count);
			access_upgrade();
			$ajax_response = $secs_remaining;
	
		// Somebody trying to cheat (no sid sent)
		} else if (!isset($_GET['sid'])) {
			whos_online("kilcheat");
			if (isset($_SESSION['user']) && isset($_SESSION['logged_in'])) {
				$message = "--- $who tried to cheat and their account was disabled ---";
				sys_msg('Dharma Admin', $message);
			}
			block_cheater();
			break;
		}
		break;

	case "stats":
		// Display Stats
		$ajax_response = display_stats();
		break;

	case "history":
		// Display History
		whos_online("history");
		$page = ereg_replace("[^[:digit:]]", "", $_GET['page']);
		$ajax_response = display_history_hof($page,'history');
		break;
		
	case "history_rss":
		// Display History RSS feed
		whos_online("hist_rss");
		$ajax_response = display_history_rss();
		break;
		
	case "leaderboard":
		// Display Reset Leaderboard
		whos_online("leaderbd");
		$page = ereg_replace("[^[:digit:]]", "", $_GET['page']);
		$ajax_response = display_leaderboard($page);
		break;
		
	case "hof":
		// Display Hall of Fame
		whos_online("hallfame");
		$page = ereg_replace("[^[:digit:]]", "", $_GET['page']);
		$ajax_response = display_history_hof($page,'hof');
		break;
		
	case "lockdown":
		// Check for lockdown condition
		$ajax_response = check_lockdown();
		break;
	
	case "setlockdown":
		// Process lockdown request
		$ajax_response = reservation_request("L");
		header('Location: http://www.enterthehatch.com/ads_google.php');
		break;
	
	case "ekodream":
		// Check for dream condition
		$ajax_response = check_ekodream();
		break;
	
	case "setekodream":
		// Process dream request
		$ajax_response = reservation_request("D");
		header('Location: http://www.enterthehatch.com/ads_google.php');
		break;
	
	case "armoury":
		// Check if they are locked in the armoury
		$ajax_response = check_armoury();
		break;
	
	case "reserve":
		// Process reservation request
		reservation_request("R", $_POST['reserve_for']);
		header('Location: http://www.enterthehatch.com/ads_google.php');
		break;
	
	case "whosonline":
		// Display Whos online
		whos_online("L4online");
		$page = ereg_replace("[^[:digit:]]", "", $_GET['page']);
		$ajax_response = display_whosonline($page);
		break;
		
	case "chathistory":
		// Display Chat History
		whos_online("ChatHist");
		$page = ereg_replace("[^[:digit:]]", "", $_GET['page']);
		$ajax_response = display_chathistory($page);
		break;
		
	case "comms":
		// Display Shoutbox
		whos_online("chat");
		$ajax_response = shoutboxView();
		break;
		
	case "poll":
		// Check for new Shout Messages
		$ajax_response = shoutboxPoll();
		break;

	case "comms_prompt":
		// Toggle public/private chat?
		if (isset($_SESSION['logged_in']) && $_SESSION['access_level'] >= 3 && $_GET['toggle'] == 'y') {
			$_SESSION['private_chat'] = (isset($_SESSION['private_chat']))? null: true;
		}
		$ajax_response = shoutboxForm();	
		break;


	default:
		break;
	}
	
	if ($_POST['q'] == 'comm') {
		$ajax_response = shoutboxProcess();
	}
		
	echo $ajax_response;
	exit;

} else {
	// Update Whos Online 
	whos_online("pageload");
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<meta name="generator" content="Adobe GoLive" />
		<title>Enter The Hatch: Push The Button</title>
		<meta name="description" content="Experience the tension of the hatch from the ABC LOST tv series. Enter the numbers every 108 minutes and see how long you can all keep the timer running." />
		<meta name="keywords" content="lost season 4, LOST, ABC LOST, the hatch, 4 8 15 16 23 42, dharma initiative, the numbers, push the button" />
		<link href="css/dharma.css" rel="stylesheet" type="text/css" media="all" />
		<link href="css/recommend.css" rel="stylesheet" type="text/css" media="all" />
		<meta name="y_key" content="ff08acdd1975e021" />
		<link rel="alternate"  type="application/rss+xml" title="Enter the Hatch: Live Event feed" href="http://feeds.feedburner.com/EnterTheHatchLatestEvents" />
		<script type="text/javascript">var secsRemaining = ''; var screenName = null; var privChat = false;</script>
		<script type="text/javascript">
		
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-37828962-1']);
		  _gaq.push(['_trackPageview']);
		
		  (function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		
		</script>
		<script charset="utf-8" type="text/javascript" src="src/soundmanager2.js"></script>
		<script charset="utf-8" type="text/javascript" src="src/dharma.js"></script>
		<script type="text/javascript">
			soundManager.setup({
			  // location: path to SWF files, as needed (SWF file name is appended later.)
			  url: '/src/swf/',
			
			  // optional: version of SM2 flash audio API to use (8 or 9; default is 8 if omitted, OK for most use cases.)
			  // flashVersion: 9,
			
			  // use soundmanager2-nodebug-jsmin.js, or disable debug mode (enabled by default) after development/testing
			  // debugMode: false,
			
			  // good to go: the onready() callback
			  onready: function() {
				// SM2 has started - now you can create and play sounds!
				soundManager.createSound('pong','audio/pong.mp3');
				soundManager.createSound('klaxon','audio/klaxon.mp3');
				soundManager.createSound('shuffle','audio/shuffle.mp3');
				soundManager.createSound('key_press','audio/key_press.mp3');
				soundManager.createSound('timer_tick','audio/timer_tick.mp3');
				soundManager.createSound('code_ok','audio/code_ok.mp3');
				soundManager.createSound('system_failure','audio/system_failure.mp3');
			  },
			
			  // optional: ontimeout() callback for handling start-up failure
			  ontimeout: function() {
				// Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
				// See the flashblock demo when you want to start getting fancy.
			  }
			});			
		</script>
	</head>

	<body onload="firstLoad();">
		<div class="content">
			<div style="display: none;" id="armoury">
					<img src="img/armoury.jpg">
			</div>
			<div id="clock">
				<span id="hundred" class="time minutes"><img id='hg1' src="img/hg1.png" style="display:none;"/></span><span id="ten" class="time minutes"><img id='hg2' src="img/hg2.png" style='display:none;'/></span><span id="one" class="time minutes"><img id='hg3' src="img/hg3.png" style='display:none;'/></span><span id="tenth" class="time seconds"><img id='hg4' src="img/hg4.png" style='display:none;'/></span><span id="hundredth" class="time seconds"><img id='hg5' src="img/hg5.png" style='display:none;'/></span><img id="line" src="img/black.gif" height="2" width="194" />
			</div>
			<div id="faq">
				<h1>Frequently Asked Questions</h1>
				<h2>What code do I have to type?</h2>
				<p>The numbers are "4 8 15 16 23 42", including spaces, excluding quotes.</p>
				<h2>Where and when can I type the numbers?</h2>
				<p>Go to the 'Home' screen to type the numbers. They should appear on the computer screen as you type. Press the enter or return key to submit the numbers. You must use the number keys at the top of your keyboard - the keypad cannot be used. You can only enter the numbers in the last four minutes of the timer, when the alarm sounds.</p>
				<h2>What are Access Levels?</h2>
				<p>Access Levels are granted as you Push The Button (PTB). The more you push the button, the higher level you will be granted, up to Level 9. Each access level unlocks a new secret feature of the hatch. You get a reset point every time you are the first to PTB or for every 5 consecutive PTB you make in solo play.</p>
				<h2>How many reset points do I need for the next level?</h2>
				<p>Please login so we can calculate your current Access Level.</p>				<h2>What happens if the timer expires?</h2>
				<p>Have you never watched LOST?!?! If you want to see a system failure, simply disconnect your internet connection when the timer reaches the 4 minute mark... but please don't blame us if your computer implodes.</p>
				<h2>Can I play solo?</h2>
				<p>Yes, although keeping the timer going is a group effort, we also count the number of consecutive pushes you make, so you can see how long you can personally keep the timer going whilst contributing to the group record. Every time you PTB two or more times in succession, a message will appear in chat to inform everyone you are on a roll... and if you break your own personal record, it will say this too.</p>
				<p>Any valid attempt to PTB will count towards your solo score, so even if you are not the first to PTB or you PTB when the timer is reserved, it will still count towards your solo score. Please note, if you PTB whilst the timer is reserved it will not reset the timer, so you might need to PTB AGAIN if no-one else does to prevent system failure.</p>
				<h2>Why was the button reserved?</h2><p>It is possible for registered users to reserve some of the pushes available each day.<br/>Try again another time, or register a screen name!</p>
						<h2>I missed my reserve, can I get a refund?</h2><p>Sorry, no. Dharma Credits allow you to reserve the button for the first minute. Even if you don't take the opportunity to actually push the button yourself, you are still preventing other people from pushing the button during that time. Unused Dharma Credits are also non-refundable.</p>
										<h2>Any other tips?</h2>
				<p>You can hover your mouse over flags, screen names in chat messages, and statistic headings to get more info. Make sure you have cookies enabled on your browser. Play nice in chat, and have fun. Namaste and Good Luck!</p>
			</div>
			<div id="computer">
				<div id="front">
					<div id="screen">
						&gt;:<img class="cursor" src="img/green.png" />
	  				</div>
				</div>
				<div id="status">
					<noscript>&gt;: Sorry, this site needs Javascript to work.<img class="cursor" src="img/green.png" /></noscript>
				</div>
				<div id="back">
					<p>Every 108 minutes, the button must be pushed. From the moment the alarm sounds, you will have four minutes to enter the code into the microcomputer processor.</p>
	    			<p> Either you or your partners must input the code. It is highly recommended that you and your partners take alternating shifts. In this manner you will all stay fresh and alert.</p>
					<p>Congratulations! Until your replacements arrive, the future of the project is in your hands. On behalf of the Degroots, Alvar Hanso and all of us at the Dharma Initiative, thank you. Namaste. And good luck.</p>
					<img id="okButton" onmousedown="okClicked();" onmouseup="okReleased(); doFlipToPage('home');" onmouseout="okReleased();" src="img/ok.gif" />
				</div>
				<div id="orientation">
					<object width="300" height="230"><param name="movie" value="http://www.youtube.com/v/PZ4VuFjxo40"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/PZ4VuFjxo40" type="application/x-shockwave-flash" wmode="transparent" width="300" height="230"></embed></object>
				</div>
				<div id="stats">
				