<?php
	if(!session_is_registered('last_topic')) session_register('last_topic');
	if(!session_is_registered('last_post')) session_register('last_post');
	if(!session_is_registered('mobile_logged_in')) $phorum_error = 'Prispievať do fóra môžu len zaregistrovaní a prihlásení užívatelia!';
	
	$actions = array('create_topic', 'create_topic_confirm', 'topic', 'insert_post', 'delete_topic', 'delete_post');
	$protected_actions = array('create_topic', 'create_topic_confirm', 'insert_post', 'delete_topic', 'delete_post');
	$action = (key_exists('action', $_GET) && in_array($_GET['action'], $actions) && (!in_array($_GET['action'], $protected_actions) || session_is_registered('mobile_logged_in'))) ? $_GET['action'] : '';
	
	$reply = (isset($_GET['reply'])) ? $_GET['reply'] : 0;
	$get_reply = isset($_GET['reply']) ? '&amp;reply='.$_GET['reply'] : '';
	if(!isset($_SESSION['threads']))
	{
		$_SESSION['threads'] = true;
	}
	$threads = $_SESSION['threads'];
	
	//********************************** VLOŽENIE NOVEJ TÉMY **************************************
	if($action=='create_topic_confirm')
	{
		$meno = str_replace(' ', '', $_POST['meno']);
		if(trim($meno)!='')
		{
			$meno = addslashes(htmlspecialchars($_POST['meno']));
			$popis = addslashes(htmlspecialchars($_POST['popis']));
			if($meno!=$_SESSION['last_topic'])
			{
				$parent = $_POST['parent'];
				if($parent!=0)
				{
					$query = "INSERT INTO `mobile_phorum_topics` 
								( `ID` , `name` , `popis` , `vytvoril` , `vytvorena` , `posledny_prisp` , `posl_prisp_time` , `parent_topic` )
							  VALUES 
							  	( '', '$meno', '$popis', '".$_SESSION['log']."', NOW( '0000-00-00 00:00:00' ) , '-1', '0000-00-00 00:00:00', '$parent')";
					$check = $dba->ExecuteQuery($query);
					if($check)
					{
						$action = '';
						$phorum_error = 'Téma bola úspešne vytvorená!';
						$_SESSION['last_topic'] = $meno;
					}
					else 
					{
						$phorum_error = 'Chyba pri zápise do databázy, vyskúšajte to prosím ešte raz!';
						$action = 'create_topic';
						$_GET['parent'] = $_POST['parent'];
					}
				}
				else 
				{
					$phorum_error = 'Chyba v prenášaní parent člena! Vráťte sa prosím na hlavnú stránku fóra a opäť kliknite na odkaz vytvoriť tému.';
					$action = 'create_topic';
					$_GET['parent'] = $_POST['parent'];
				}
			}
			else
			{
				$action = '';
			}
		}
		else 
		{
			$phorum_error = 'Nezadali ste názov témy!';
			$action = 'create_topic';
			$_GET['parent'] = $_POST['parent'];
		}
	}
	//********************************** KONIEC VLOŽENIE NOVEJ TÉMY **************************************	
	//********************************** ZMAZANIE TÉMY ***************************************************
	if($action=='delete_topic')
	{
		$id = (key_exists('id', $_GET)) ? $_GET['id'] : 0;
		if($id!=0)
		{
			$query = "SELECT vytvoril FROM mobile_phorum_topics WHERE ID=$id AND visible='v' limit 0, 1";
			$result = $dba->GetResult($query);
			$row = mysql_fetch_array($result);
			$vytvoril = $row['vytvoril'];
			if(($vytvoril!='' && $vytvoril==$_SESSION['log']) || in_array($_SESSION['my_id'], $admins))
			{
				$query = "UPDATE mobile_phorum_topics SET visible='h' WHERE ID=$id limit 1";
				$check = $dba->ExecuteQuery($query);
				$phorum_error = ($check) ? 'Téma úspešne zmazaná' : 'Chyba pri mazaní témy';
			}
			$action = '';
		}
	}
	//********************************** KONIEC ZMAZANIE TÉMY ***************************************************
	//********************************** ZMAZANIE PRÍSPEVKU ***************************************************
	if($action=='delete_post' && in_array($_SESSION['my_id'], $admins))
	{
		$id = (key_exists('id', $_GET)) ? $_GET['id'] : 0;
		if($id!=0)
		{
			$query = "DELETE FROM mobile_phorum_posts WHERE ID=$id limit 1";
			$dba->ExecuteQuery($query);
			$action = 'topic';
			$_GET['topic_id'] = $_SESSION['last_viewed_topic'];
		}
	}
	//********************************** KONIEC ZMAZANIE TÉMY ***************************************************
	
	//********************************** VLOŽENIE PRÍSPEVKU **************************************
	if($action=='insert_post')
	{
		$topic_id = (key_exists('topic_id', $_POST)) ? $_POST['topic_id'] : 0;
		$topic_parent = (key_exists('topic_parent', $_POST)) ? $_POST['topic_parent'] : 0;
		$text = (key_exists('text', $_POST)) ? str_replace(' ', '', $_POST['text']) : '';
		if($topic_id!=0 && $topic_parent!=0 && $text!='')
		{
			$text = addslashes(htmlspecialchars($_POST['text']));
			$text = nl2br($text);
//			if(in_array($_SESSION['my_id'], $admins))
			{
//			    $text = str_replace(' ', '&nbsp;', $text);
			}
			if($text!=$_SESSION['last_post'])
			{
				$query = "INSERT INTO `mobile_phorum_posts` 
							( `ID` , `pridal` , `cas` , `parent_topic` , `parent_main_topic` , `text` )
						  VALUES 
						  	('', '".$_SESSION['my_id']."', NOW( '0000-00-00 00:00:00' ) , '$topic_id', '$topic_parent', '$text')";
				$check1 = $dba->ExecuteQuery($query);
				$get_reply = '';
				//vytvorenie vektora
				$max_id = $dba->Max('mobile_phorum_posts', 'ID');
				$vector = '';
				if($_POST['post_reply'] != 0)
				{
					$row = $dba->GetRow2('mobile_phorum_posts', '*', 'ID', $_POST['post_reply']);
					$vector .= $row['vector'];
					//notifikacia
//					if($row['notify'] != 0)
//					{
//						$predmet = 'Odpoveď na Váš odkaz s ID '.$_POST['post_reply'];
//						$notify_to = $row['notify'];
//						$original_mess = $row['text'];
//						$original_mess_date = $row['datum'];
//						$sprava = "Na Váš odkaz pridaný o $original_mess_date:<br/>$original_mess<br/><br/>odpovedal $datum $meno:<br/>".$text;
//						$query = "INSERT INTO mobile_posta (predmet, text, user_from, user_to, cas, visible_sender) values ('$predmet', '$sprava', -1, ".$notify_to.", NOW(), '0')";
//						$dba->ExecuteQuery($query);
//					}
					//END
				}
				else 
				{
					$vector .= '#';
				}
				$vector .= str_pad(100000 - $max_id, 5, '0', STR_PAD_LEFT).'#';
				$query = "UPDATE mobile_phorum_posts SET vector = '$vector' WHERE id='$max_id' limit 1";
				$dba->ExecuteQuery($query);
				//koniec vektora
				
				$query = "UPDATE `mobile_phorum_topics` SET 
						`posledny_prisp` = '".$_SESSION['my_id']."',
						`posl_prisp_time` = NOW( '0000-00-00 00:00:00' ) WHERE `ID` = '$topic_id' LIMIT 1";
				$check2 = $dba->ExecuteQuery($query);
				$phorum_error = '';
				if($check1)	
				{
					$phorum_error .= "Príspevok úspešne vložený<br />\n";
					$_SESSION['last_post'] = $text;
//					$mails = array ('pesto@peterpech.com', 'miso85@t-zones.sk');
					$mails = array ('pesto@peterpech.com');
					foreach($mails as $mail)
					{
						$subject = "4mobile forum";
				   		$sprava = $_SESSION['log']." | téma ".$_POST['topic_name']." : ".$text;
				   		$headers = "From:4mobile <4mobile@4mobile.sk>\n";
				   		$headers .= "Content-Type: text/html; charset=iso-8859-2\n";
//				   		mail($mail,  $subject, $sprava, $headers);
					}
				}
				else 
				{
					$phorum_error .= "Chyba pri vkladaní príspevku!<br />\n";
				}
				if($check2)	
				{
					$phorum_error .= "Stav témy úspešne aktualizovaný<br />\n";
				}
				else 
				{
					$phorum_error .= "Chyba pri aktualizácii stavu témy!<br />\n";
				}
			}
			$_GET['topic_id'] = $topic_id;
			$action = 'topic';
		}
		else 
		{
			if($text=='') $phorum_error = 'Nezadali ste text príspevku!';
			else $phorum_error = 'Neprenesený topic id alebo main parent';
			$_GET['topic_id'] = $topic_id;
			$action = 'topic';
		}
		
	}
	//********************************** KONIEC VLOŽENIE PRÍSPEVKU **************************************
	
	//********************************** RÁTANIE TÉM **************************************
	// pole hlavnych tem
	$query = "SELECT * FROM mobile_phorum_main_topics ORDER BY ID ASC";
	$result = $dba->GetResult($query);
	$phorum_main_topics = array();
	while($row = mysql_fetch_array($result))
	{
		$phorum_main_topics[$row['ID']] = $row['name'];
	}
	
//	if($action=='')
//	{
		$query = "SELECT 
					a.ID, a.name, a.popis, a.vytvoril, a.vytvorena, a.posledny_prisp, a.posl_prisp_time, a.parent_topic, b.login as posledny  
				  FROM mobile_phorum_topics a, mobile_users b 
				  WHERE a.posledny_prisp=b.ID AND a.visible='v'
				  ORDER BY a.ID DESC";
		$result = $dba->GetResult($query);
		$phorum_topics = array();
		while($row = mysql_fetch_array($result))
		{
			$phorum_topics[$row['parent_topic']][$row['ID']]['name'] = $row['name']; 
			$phorum_topics[$row['parent_topic']][$row['ID']]['popis'] = $row['popis']; 
			$phorum_topics[$row['parent_topic']][$row['ID']]['vytvoril'] = $row['vytvoril']; 
			$phorum_topics[$row['parent_topic']][$row['ID']]['vytvorena'] = $row['vytvorena']; 
			$phorum_topics[$row['parent_topic']][$row['ID']]['posledny_prisp'] = $row['posledny'];
			$phorum_topics[$row['parent_topic']][$row['ID']]['posledny_prisp_id'] = $row['posledny_prisp'];
			$phorum_topics[$row['parent_topic']][$row['ID']]['posl_prisp_time'] = $row['posl_prisp_time'];
			$phorum_topics[$row['parent_topic']][$row['ID']]['parent_topic'] = $row['parent_topic'];
			$topic_posts_cnt[$row['parent_topic']][$row['ID']] = 0;
		}
		
		$query = "SELECT a.parent_topic, a.parent_main_topic, b.visible, b.ID 
					FROM mobile_phorum_posts a, mobile_phorum_topics b 
					WHERE a.parent_topic=b.ID AND b.visible='v'";
		$result = $dba->GetResult($query);
		while($row = mysql_fetch_array($result))
		{
			$topic_posts_cnt[$row['parent_main_topic']][$row['parent_topic']]++;
		}
		//********************************** KONIEC RÁTANIE TÉM **************************************
//	}
?>
<script language="JavaScript" type="text/javascript">
function fnConfirm1(link)
{
	if (confirm('Naozaj chcete zmazať túto tému?'))
	{
		window.location = link;
	}
}
function fnConfirm2(link)
{
	if (confirm('Naozaj chcete zmazať tento príspevok?'))
	{
		window.location = link;
	}
}

</script>
<div id="register_form01">
	  <div id="menu01_head">:: fórum</div>
	<?php
	
	if(isset($phorum_error)) echo "<div id=\"red\" align=\"center\">$phorum_error</div>";
	//********************************** VÝPIS MAIN TÉM A PODTÉM **************************************
	if($action=='')
	{
		foreach($phorum_main_topics as $pmtk => $main_topic)
		{
			echo "<div class=\"phorum_main_topic\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
					<tr>
						<td>:: $main_topic</td>
						<td align=\"right\">";
			if(session_is_registered('my_id')) echo "<a href=\"index.php?module=forum&amp;action=create_topic&amp;parent=$pmtk\" class=\"phorum_new_cat_link\">vytvor tému v tejto kategórii</a>";
			echo "</td>	</tr></table></div>";
			if(key_exists($pmtk, $phorum_topics) && is_array($phorum_topics[$pmtk]))
			{
				echo "<div class=\"phorum_topic\"><table width=\"100%\" cellspacing=\"1\">";
				foreach($phorum_topics[$pmtk] as $ptk => $topic)
				{
					echo "<tr><td onclick=\"location.href='index.php?module=forum&amp;action=topic&amp;topic_id=$ptk'\" style=\"cursor: hand; cursor: pointer;\" width=\"55%\" class=\"phorum_topic_cell_left\">";
					echo '<span style="font-size: 10pt;"><b>'.stripslashes($topic['name']).'</b></span><br />';
					if($topic['popis']!='') echo "<span class=\"phorum_topic_popis\">".stripslashes($topic['popis'])."</span><br />";
					echo "Vytvoril: <span class=\"cervena\">".$topic['vytvoril']."</span> </td>";
					echo "<td class=\"phorum_topic_cell\" align=\"center\" width=\"15%\" onclick=\"location.href='index.php?module=forum&amp;action=topic&amp;topic_id=$ptk'\" style=\"cursor: hand; cursor: pointer;\">".$topic_posts_cnt[$pmtk][$ptk]." príspevkov</td>";
					echo "<td align=\"center\" class=\"phorum_topic_cell\" onclick=\"location.href='index.php?module=forum&amp;action=topic&amp;topic_id=$ptk'\" style=\"cursor: hand; cursor: pointer;\">";
					if($topic_posts_cnt[$pmtk][$ptk]>0)	echo "Posledný<br /> ".$topic['posl_prisp_time']."<br /> od <span id=\"red\">".$topic['posledny_prisp']."</span>";
					else echo "Ešte nebol pridaný žiadny príspevok";
					echo "</td>";
					if((key_exists('my_id', $_SESSION) && in_array($_SESSION['my_id'], $admins)) || (session_is_registered('log') && $topic['vytvoril']==$_SESSION['log'])) 
					{
						echo "<td class=\"phorum_topic_cell\"><a href=\"javascript: fnConfirm1('index.php?module=forum&action=delete_topic&id=$ptk');\" class='refresh'>zmazať</a></td>";
					}
					echo "</tr>";
				}
				echo "</table></div>";
			}
		}
	}
	//********************************** KONIEC VÝPIS MAIN TÉM A PODTÉM **************************************
	
	//********************************** FORM VLOZENIE NOVEJ TEMY **************************************
	if($action=='create_topic' && key_exists('parent', $_GET))
	{
		echo "<form action=\"index.php?module=forum&amp;action=create_topic_confirm\" method=\"post\">";
		echo "<div id=\"melodia_div\">";
		echo "Názov témy: <input id=\"form_field01\" type=\"text\" name=\"meno\" maxlength=\"50\" size=\"50\"/>* povinné<br />";
		echo "Stručný popis témy: <input id=\"form_field01\" type=\"text\" name=\"popis\" maxlength=\"100\" size=\"50\"/><br />";
		echo "<input type=\"hidden\" name=\"parent\" value=\"".$_GET['parent']."\" />";
		echo "<input id=\"form_button01\" type=\"submit\" name=\"Submit\" value=\"OK\"/>&nbsp;<input id=\"form_button01\" type=\"reset\" name=\"reset\" value=\"Reset\"/>";
		echo "</div></form>";
	}
	//********************************** KONIEC FORM VLOZENIE NOVEJ TEMY **************************************
	
	//********************************** PREZERANIE TEMY **************************************
	$topic_id = (key_exists('topic_id', $_GET)) ? $_GET['topic_id'] : '';
	if($action='topic' && $topic_id!=0)
	{
		$query = "SELECT 
					a.ID, a.name, a.popis, a.vytvoril, a.vytvorena, a.posledny_prisp, a.posl_prisp_time, a.parent_topic, b.login as posledny  
				  FROM mobile_phorum_topics a, mobile_users b 
				  WHERE a.posledny_prisp=b.ID AND a.ID=$topic_id";
		$result = $dba->GetResult($query);
		$num = mysql_num_rows($result);	
		if($result)
		{
			$topic = mysql_fetch_array($result);
			$topic_parent = $topic['parent_topic'];
			echo "<div class=\"phorum_topic\"><table width=\"100%\" cellspacing=\"1\">";
			echo "<tr><td width=\"55%\" class=\"phorum_topic_cell_left\">";
			echo '<b>'.stripslashes($topic['name']).'</b><br />';
			if($topic['popis']!='') echo "<span class=\"phorum_topic_popis\">".stripslashes($topic['popis'])."</span><br />";
			echo "Vytvoril: <span class=\"cervena\">".$topic['vytvoril']."</span> </td>";
			echo "<td class=\"phorum_topic_cell\" align=\"center\" width=\"15%\">".$topic_posts_cnt[$topic['parent_topic']][$topic['ID']]." príspevkov</td>";
			echo "<td align=\"center\" class=\"phorum_topic_cell\">";
			if($topic_posts_cnt[$topic['parent_topic']][$topic['ID']]>0) echo "Posledný<br /> ".$topic['posl_prisp_time']."<br /> od <span id=\"red\">".$topic['posledny']."</span>";
			else echo "Ešte nebol pridaný žiadny príspevok";
			echo "</td></tr></table></div>";
			if(session_is_registered('mobile_logged_in'))
			{
				?>
				<script language="javascript">
				function AddSmile(s)
				{
				   document.forms.frm.text.value += ' ' + s + ' ';
				   document.forms.frm.text.focus();
			   	}
			
				</script>
				<div id="melodie_01">
				<form name="frm" style="padding-top: 10px;" action="index.php?module=forum&amp;action=insert_post" method="post">
				<table border="0" cellspacing="0" cellpadding="0" align="center">
				<?php
				
					if($reply != 0 && $get_reply != '')
					{
					  	$row= mysql_fetch_assoc(mysql_query("SELECT a.*, b.login as pridal_login FROM mobile_phorum_posts a, mobile_users b WHERE a.pridal = b.ID AND a.ID='$reply' limit 0,1"));
				?>
				  <tr> 
				      <td valign="top" align="right" width="75">Odpoveď na:</td>
				      <td valign="top" align="left" width="371" style="padding: 3px;" bgcolor="#171717"> 
				        <?php
				        
				        	echo "<span id=\"red\"><b>".$row['pridal_login']."</b></span> | ";
							echo "pridané: ".$row['cas']."<br />";
							echo fnSmile(fnSmileys(stripslashes(fnCutLong($row['text']))));
				        
				        ?>
				      </td>
				      <td valign="top" width="65"></td>
				  </tr>
				  <?php
					}
					?>
				  <tr> 
				      <td valign="top" align="right">Správa:&nbsp;</td>
				      <td valign="top" align="left"> 
				        <textarea id="form_field01" rows="8" cols="70" name="text"></textarea><br />
				        <input type="hidden" name="topic_parent" value="<?php echo $topic_parent; ?>" />
				        <input type="hidden" name="topic_id" value="<?php echo $topic_id; ?>" />
				        <input type="hidden" name="topic_name" value="<?php echo $topic['name']; ?>" />
				      </td>
				      <td valign="top"><?php  
				      for($j=1;$j<=20;$j++)
				      {
				      	echo"<a href=\"javascript:AddSmile('s".$j."')\"><img src=\"images/smile/".$j.".gif\" border=\"0\" align=\"top\" style=\"padding-bottom: 1.5px;\" alt=\"\"/></a>&nbsp;";
				      	if($j%3==0) echo "<br />";
				      }
				      ?></td>
				  </tr>
				  <tr> 
				    <td></td>
				    <td align="left" valign="top">
				            <input id="form_button01" type="submit" name="Submit" value="Pošli"/>
				            <input id="form_button01" type="reset" name="reset" value="Reset"/>
				            <input type="hidden" name="post_reply" value="<?php echo $reply; ?>"/>
				    </td>
				  </tr>
				  <tr> 
				    <td>&nbsp;</td>
				    <td align="left" valign="top">
				    </td>
				  </tr>
				  </tr>
				<!--  <tr> 
				  	<form name="frm2" action="index.php?module=forum&amp;action=change_thread" method="post">
				    <td align="right">
				    	Vlákna:</td>
				    <td align="left"> <select name='threads' id="form_field01" onchange="document.forms.frm2.submit();">
				    	<option value='1'<?php if($threads) echo " selected='selected'"; ?>>Zapnuté</option>
				    	<option value='0'<?php if(!$threads) echo " selected='selected'"; ?>>Vypnuté</option>
				    	</select>
				    </td>
				    </form>
				  </tr>-->
				</table></form>
				</div>
				<?php
			}
			if($num>0)
			{
				$i = (key_exists('i', $_GET)) ? $i = $_GET['i'] : 1;
				$query = "SELECT ID FROM mobile_phorum_posts WHERE parent_topic=$topic_id";
				
				$chunk = $dba->GetLimit($query);
				$lim = $chunk[0];
				$stranok = $chunk[2];
				$order_by = ($threads) ? 'vector ASC' : 'ID DESC';
				$query = "SELECT a.*, b.login as pridal_login, b.mail as mail, b.icq, b.msn, b.avatar FROM mobile_phorum_posts a, mobile_users b WHERE a.pridal=b.ID AND a.parent_topic=$topic_id ORDER BY $order_by limit $lim, $nastranu";
//				dump($query);
				$result = $dba->GetResult($query);
				echo "<div align=\"center\"><a href=\"index.php?module=forum&amp;action=topic&amp;topic_id=$topic_id\" class=\"refresh\">[ REFRESH ]</a>  
				<a href=\"index.php?module=forum\" class=\"refresh\">[ ZOZNAM TÉM ]</a>
				</div>";
				echo "<div style='width: 94%; text-align: right; margin-left: auto; margin-right: auto;'>";
				$_SESSION['last_viewed_topic'] = $topic_id;
				fnNavi($i, $stranok, "module=forum&amp;action=topic&amp;topic_id=$topic_id");
				fnWriteForum($result);
				fnNavi($i, $stranok, "module=forum&amp;action=topic&amp;topic_id=$topic_id");
				echo "</div>";
			}
			else 
			{
				echo "<div id=\"red\" align=\"center\">V tejto téme ešte nie je žiadny príspevok</div>";
			}
		}
		else 
		{
			echo "<div id=\"red\" align=\"center\">Chyba pri výbere z databázy</div>";
		}
	}
	//********************************** KONIEC PREZERANIE TEMY **************************************

	//********************************** VYPIS USEROV **************************************
//	$query = "SELECT a.user_id, b.login FROM mobile_logged_users a, mobile_users b WHERE a.user_id = b.ID";
//	$result = $dba->GetResult($query);
//	echo '<br /><b>Online používatelia:</b ';
//	$i = 0;
//	while($row = mysql_fetch_array($result))
//	{
//		if($i>0) echo ", ";
//		echo $row['login'];
//		$i++;
//	}
	  
	  ?>
</div>