<?php
	session_start();
	include('database.php');
	DB_connexion(); 
	
	/*if(!isset($_SESSION['logged']) )
	{		header ('Location: interdiction.php');
	}
	
	if($_SESSION['logged']== "no")
	{
		header ('Location: interdiction.php');
	} */
	
/******** eviter des soumission intempestives lors d'un reload de la page F5  ************************************/	
	if(!empty($_POST) )
	{
		$_SESSION['sauvegarde_formulaire'] = $_POST ;
     
		$page_actuelle = $_SERVER['PHP_SELF'] ;
		if(!empty($_SERVER['QUERY_STRING']))
		{
			$page_actuelle .= '?' . $_SERVER['QUERY_STRING'] ;
		}
     
		header('Location: ' . $page_actuelle);
		exit;
	}
	
	if(isset($_SESSION['sauvegarde_formulaire']))
	{
		$_POST = $_SESSION['sauvegarde_formulaire'] ;
		unset($_SESSION['sauvegarde_formulaire']);		
	}	
/************************************************************************/	
	
			$chat_msg = '';
			$chat_destinataires= '';
	
			//vérifications des données (éviter les attaques SQL)
            
			if (isset($_GET['msg'])) {
				 $chat_msg = htmlspecialchars($_GET['msg'], ENT_QUOTES); //protection du message
			}

			if (isset($_GET['destinataire'])) {
				 $chat_destinataires = htmlspecialchars($_GET['destinataire'], ENT_QUOTES); //protection des destinataires
			}
	
	
?>


<?php			

function gestion_icons($str)
{
				$associative_icons = array( ':)'  => '0.gif',
											':(' => '1.gif',
											':P' => '2.gif',
											':D' => '3.gif',
											':S'  => '4.gif',
											':O'  => '5.gif',
											':=)'  => '6.gif',
											':|H' => '7.gif',
											':X'  => '8.gif',
											':-*' => '9.gif');
								
				$icons = array( ':)' , ':(' , ':P' , ':D', ':S', ':O', ':=)', ':|H', ':X',':-*');						

				for($i = 0; $i < 9; $i++)
				{
					$n = mb_substr_count($str, $icons[$i]);
					if($n != 0)
					{
						$v = $associative_icons[$icons[$i]];
						//echo "<img src='images/chat/1.gif'";  
?>
						<img src="images/chat/<?php echo $v ?>"/>
<?php		
						//echo '<img src="images/chat/.$v  .'>';
						echo "<br>";
						
					}
					
				}	

}

								
?>			

<!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="Description" content="Site perso,cours,ouvrages" />
<meta name="Keywords" content="WEBSITE perso " />
<meta name="Distribution" content="Global" />
<meta name="Robots" content="" />
<meta http-equiv="Content-Language" content="fr" />
<meta name="rating" content="general" />
<meta name="author" content="Patrice DELPY" />
<meta name="copyright" content="Copyright 2013" />
<meta name="generator" content="Patoche" />
<title>Patoche WEBSITE - 2013 - Template du site - en cours de développemment ...</title>
<!---------------------------------------------------------->	
<?php
		include('include_css_template_commun.php');
		include('include_css.php');
		include('css_tools_skill.php');
		include('include_javascript.php');
?> 

<style>
   select.connexion , ul.connexion  { height: 302px; overflow: auto; width: 202px; border: 1px solid #000;  margin:0px 0px 0px 10px;}
   //ul.connexion { list-style-type: none; margin: 0; padding: 0; overflow-x: hidden; }
 
	ul.connexion { list-style-type: none; margin:0px 0px 0px 10px; padding: 0; overflow-x: hidden; }
	
	.paddingClass{
       margin:20px;
		padding:5px;
	}
 
</style>

<link href="css/tchat_style.css" rel="stylesheet" type="text/css">	

<script>

function select_all_connected() 
{

 //select, ul { height: 100px; overflow: auto; width: 100px; border: 1px solid #000; }
 /*  
   .blase {
			list-style-type: none;
	}
   
    .blase select  { height: 100px; overflow: auto; width: 100px; border: 1px solid #000; }
   .blase ul { list-style-type: none; margin: 0; padding: 0; overflow-x: hidden; }
   .blase li { margin: 0; padding: 0; }
   label { display: block; color: WindowText; background-color: Window; margin: 0; padding: 0; width: 100%; }
   label:hover { background-color: Highlight; color: HighlightText; }*/

			var selected = [];
			
			var checkbox = document.getElementsByName('users[]');
			for(var i=0; i< checkbox.length; i++)
			{
				checkbox[i].checked = true;
				selected.push(checkbox[i].value);
			}  
			
			var str = selected.toString();
			
			var xhr = getXhr();
								
			xhr.onreadystatechange = function()
			{
				// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					retour = xhr.responseText;
				}
			}

			xhr.open("POST","sauvegarde_session.php",true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.send("users="+str);		
			
}

function unselect_all_connected() 
{
			var selected = [];
			
			var checkbox = document.getElementsByName('users[]');
			for(var i=0; i< checkbox.length; i++)
			{
				checkbox[i].checked = false;
				
			}  
			
			var str = ""
			
			
			var xhr = getXhr();
								
			xhr.onreadystatechange = function()
			{
				// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					retour = xhr.responseText;
				}
			}

			xhr.open("POST","sauvegarde_session.php",true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.send("users="+str);		
}

function call_update()
{
			ajax_routine(); 
			setTimeout("call_update()", 1000); //appelle la fonction 1 fois par  seconde
}

function send_message()
{

			// liste des personnes qui vont recevoir msg
			var selected = [];
			var checkbox = document.getElementsByName('users[]');
			for(var i=0; i< checkbox.length; i++)
			{
				if(checkbox[i].checked)
				{
					selected.push(checkbox[i].value);
				}
			}  

			var users = selected.toString();
			// pas de selection
			if(users.length == 0)
			{
				alert("Erreur");
			}
			else
			{
				// 
				var msg = document.getElementById("msg").value;
				var xhr = getXhr();
								
				xhr.onreadystatechange = function()
				{
					// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
					if(xhr.readyState == 4 && xhr.status == 200)
					{
						retour = xhr.responseText;
					}
				}

				xhr.open("POST","tchat_envoi_msg.php",true);
				xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
						
				xhr.send("users="+users+"&msg="+msg);
				//alert(users+msg);
				
			}
			
}

function action(id)
{
			var etat = document.getElementById(id).checked;
			ajax(id,etat);
}

function ajax(id,etat)
{
			var xhr = getXhr();
								
			xhr.onreadystatechange = function()
			{
				// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					retour = xhr.responseText;
					alert(retour);
				}
			}

			xhr.open("POST","sauvegarde_session.php",true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					

			xhr.send("id="+id+"&etat="+etat);
			
			//alert(id + etat);


					
}

function ajouter_user(element)
{
			var selected = [];

			var checkbox = document.getElementsByName('users[]');
			for(var i=0; i< checkbox.length; i++)
			{
				if(checkbox[i].checked)
				{
					selected.push(checkbox[i].value);
				}
			}  

			var str = selected.toString();
			
			var xhr = getXhr();
								
			xhr.onreadystatechange = function()
			{
				// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					retour = xhr.responseText;
				}
			}

			xhr.open("POST","sauvegarde_session.php",true);
			xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			xhr.send("users="+str);		

}

function updateChat()
{
			var xhr = getXhr();	
							
            xhr.open('GET', 'update_chat.php');
            xhr.onreadystatechange = function()
			{
                if(xhr.readyState == 4)
				{
                    var msg = xhr.responseText;
                    if (msg != '')
					{ //si la réponse du script n'est pas vide
                        document.getElementById('rafraichir').innerHTML = msg; //change le contenu du <div>
                    }
                }
            }
            
			xhr.send(null);
                
}

function getXhr()
{
			var xhr = null; 
			if(window.XMLHttpRequest) // Firefox et autres
			   xhr = new XMLHttpRequest(); 
			else if(window.ActiveXObject)
			{ // Internet Explorer 
			   try 
			   {
					xhr = new ActiveXObject("Msxml2.XMLHTTP");
			   } 
			   catch (e) 
			   {
					xhr = new ActiveXObject("Microsoft.XMLHTTP");
			   }
			}
			else 
			{ 
				// XMLHttpRequest non supporté par le navigateur 
				alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
				xhr = false; 
			} 

			return xhr;
}

function ajouter_icons(smile, id) 
{
		var element = document.getElementById(id);
		element.value += smile;
		element.focus();
}

function callUpdateChat()
{
			updateChat(); 
            setTimeout("callUpdateChat()", 1000); 
			
}
</script>

<!---------------------------------------------------------->	
</head>

<body>
<!---------------------------------------------------------->	
	<div class="main"> <!-- main -->
<!---------------------------------------------------------->	

          <div class="header">
                <div class="balise_titre">Patoche</div>
                <div class="balise_citation">
                &quot;Etre conscient que l'on est ignorant est un grand pas vers le savoir&quot;
                </div>
          </div> 
 
          <div class="banniere"></div>  

<!---------------------------------------------------------->
<?php
	
	echo '<div id="box_infos">';
			include("include_menu.php");
			
			echo '<div id="box_icon2">';
			include("connexion_membre.php");
			echo	'</div>';
			
			echo '<div id="box_icon3">';
			include("include_barre_login.php");
			echo	'</div>';

	echo	'</div>';
	$_SESSION['page_active'] = basename (__FILE__ );
?>
		

<!---------------------------------------------------------->	
            <div class="contenu"> <!-- contenu -->
<!---------------------------------------------------------->	
           
	<div id = "box_message">		
		<h2 class="retrait">Tchat du site.</h2>
	</div>
		
	<div class="centerblock">
	
				<div class="gauche">  
					<br/> 
						<div class="contenthead">Messages:</div>
							<div class="contentblock">
					
								<div id= "rafraichir">
<?php		
								
								//if( $_SESSION['login']
								if($_SESSION['logged'] != 'no' ) 
								{
										$msgs=mysql_query('SELECT * FROM tchat ORDER BY id DESC LIMIT 0,50');
										$cpt = 0;
																			
										while($infos = mysql_fetch_array($msgs)) 
										{
											$champ = date('d-m-Y ', strtotime($infos["date_mess"])) ."  à  " .date(' H:i:s', strtotime($infos["date_mess"])); 
											$utilisateur = $infos["login"];
											$txt = $infos["mess"];
											$id = $infos["id"];
											$destinataires = $infos["destinataires"];
										
											$pieces = explode(",", $destinataires);
											$nb_elements = count($pieces);
											
											$flag_login = false;
											//$ppp = gestion_icons($txt);
											
											if($utilisateur == $_SESSION['login'])
											{
												echo '<div class="pseudo"><img src="images/puce_tchat_login.jpg" />&nbsp;'.$utilisateur.'</div> ';
															if($cpt%2 == 1) /* impair */
																echo '<div class="affiche_message_pair">'.$txt.'</div>';
															else /* pair */
																echo '<div class="affiche_message_impair">'.$txt.'</div>';
															echo '<div class="date">'.$champ.'<img src="images/puce_tchat_date.jpg" /></div>';
															$cpt = $cpt + 1;
											}
											
											else
											{
											
													for($i = 0; $i < $nb_elements; $i++)
													{	
														$element = $pieces[$i];
														if($element == $_SESSION['login'])	
														{  $flag_login = true;
															echo '<div class="pseudo"><img src="images/puce_tchat_login.jpg" />&nbsp;'.$utilisateur.'</div> ';
															if($cpt%2 == 1) /* impair */
																echo '<div class="affiche_message_pair">'.$txt.'</div>';
															else /* pair */
																echo '<div class="affiche_message_impair">'.$txt.'</div>';
															echo '<div class="date">'.$champ.'<img src="images/puce_tchat_date.jpg" /></div>';
															$cpt = $cpt + 1;
														}
													}
											}		
													
										}             
								}	
?>								
								</div>
								
							</div>
				</div>
				
				
				<div class="droite">  
                <br/> 				
		
				<div class="droitehead">Membres connectés:</div>
				<!--	<div class="droiteblock"> -->

<?php
				// $etat_connexion = array("checkbox1" => "true", "checkbox2" => "true", "checkbox3" => "true");

				//$users_online = array ('Francois', 'Michel', 'Nicole', 'Veronique', 'Benoit','a','b','c','d','e','f','g', 'h','i','j','k');
				$query = "SELECT * FROM user_online WHERE connexion = 'online' ";
				$result = mysql_query($query);
				while( $data = mysql_fetch_assoc($result) )
				{	
					if($data['login'] != $_SESSION['login'])
					{
						$users_online[] = $data['login'];
					}	
				}
				
/*
				$n = count($users_online);
				 
				for($i = 0; $i < $n; $i++)
				{	
					if(count($_SESSION['etat_connexion']) != 0)
					{	
						$key = array_search($users_online[$i], $_SESSION['etat_connexion']);
						$longueur = strlen($key);
						if($longueur != 0)
						{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' checked='checked' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
						}
						else
						{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
						}
						
					}		
					else
					{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
					}		
				}
*/				
			
				//$users_online = array ('Francois', 'Michel', 'Nicole', 'Veronique', 'Benoit','a','b','c','d','e','f','g', 'h','i','j','k','l','m','n','o');
				$n = count($users_online);
			
				echo "<ul class='connexion'>";
				 
				for($i = 0; $i < $n; $i++)
				{

					if(count($_SESSION['etat_connexion']) != 0)
					{	
						$key = array_search($users_online[$i], $_SESSION['etat_connexion']);
						$longueur = strlen($key);
						if($longueur != 0)
						{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' checked='checked' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
						}
						else
						{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
						}
						
					}		
					else
					{
							echo "
							<input id='$users_online[$i]' type='checkbox' name='users[]' value='$users_online[$i]' onclick='ajouter_user(this.id)' />$users_online[$i]
							<br />";
					}		
				}	
				echo "<ul>";
				
				
?>					
    				
				<!--	</div> -->
                </div>
				
				
				<div class="icone"> 
				<img src="images/chat/0.gif" alt=":)" title=":)" onclick="ajouter_icons(':)', 'msg');" />
				<img src="images/chat/1.gif" alt=":(" title=":(" onclick="ajouter_icons(':(', 'msg');" />
				<img src="images/chat/2.gif" alt=":P" title=":P" onclick="ajouter_icons(':P', 'msg');" />
				<img src="images/chat/3.gif" alt=":D" title=":D" onclick="ajouter_icons(':D', 'msg');" />
				<img src="images/chat/4.gif" alt=":S" title=":S" onclick="ajouter_icons(':S', 'msg');" />
				<img src="images/chat/5.gif" alt=":O" title=":O" onclick="ajouter_icons(':O', 'msg');" />
				<img src="images/chat/6.gif" alt=":=)" title=":=)" onclick="ajouter_icons(':=)', 'msg');" />
				<img src="images/chat/7.gif" alt=":|H" title=":|H" onclick="ajouter_icons(':|H', 'msg');" />
				<img src="images/chat/8.gif" alt=":X" title=":X" onclick="ajouter_icons(':X', 'msg');" />
				<img src="images/chat/9.gif" alt=":-*" title=":-*" onclick="ajouter_icons(':-*', 'msg');" />
				</div>
				
				<div class="saisir_message">  
<?php
					if($_SESSION['logged'] !='no')
					{
						echo $n+1 ." connectés (" .$_SESSION['login'] .') compris';
					}	
?>				
					<textarea rows="4" cols="50" name="msg" id="msg" ></textarea> 
					<input type="hidden" name="destinataire" id="destinataire" value="" />	
					<input type="hidden"  name="action" id="action"  value="" />
					<input type="hidden"  name="membres_connect" id="membres_connect"  value="<?php echo $n; ?>" />
<?php
					if($_SESSION['logged'] !='no')
					{
						echo "	<input type='submit' value='Envoyer' onclick='send_message();' />"; 
					}
					else
					{
						echo "	<input type='submit' value='Envoyer' disabled onclick='send_message();' />"; 
	
					}
?>					
					<input type='radio' name="check_selected" value="select" onclick="select_all_connected()">Selection 
					<input type='radio' name="check_selected" value="unselect" onclick="unselect_all_connected()">Déselection
					<br>
					
<?php					
				$str = "Je suis :( mais demain :S vient manger";
				gestion_icons($str);		
?>				
				</div> 
				
	
				
	
	</div>		
	
<?php
/*
			$pipo = array ('a','b','c','d','e','f','g', 'h','i','j','k');
			
			$n = count($pipo);
			
			echo "<ul class='connexion'>";
				 
			for($i = 0; $i < $n; $i++)
			{

					if(count($_SESSION['etat_connexion']) != 0)
					{	
						$key = array_search($pipo[$i], $_SESSION['etat_connexion']);
						$longueur = strlen($key);
						if($longueur != 0)
						{
							echo "
							<input id='$pipo[$i]' type='checkbox' name='users[]' value='$pipo[$i]' checked='checked' onclick='ajouter_user(this.id)' />$pipo[$i]
							<br />";
						}
						else
						{
							echo "
							<input id='$pipo[$i]' type='checkbox' name='users[]' value='$pipo[$i]' onclick='ajouter_user(this.id)' />$pipo[$i]
							<br />";
						}
						
					}		
					else
					{
							echo "
							<input id='$pipo[$i]' type='checkbox' name='users[]' value='$pipo[$i]' onclick='ajouter_user(this.id)' />$pipo[$i]
							<br />";
					}		


			}	

			echo "<ul>";
			echo "</div>";
*/		
?>					
			<!--			 
				<ul class="connexion">					 
	  
				<li><input type="checkbox" id='$users_online[$i]' name='users[]' onclick='ajouter_user(this.id)' >Second</li>
				<li><input type="checkbox" name="chk3" id="chk3" onclick='ajouter_user(this.id)'>Third</li>
				<li><input type="checkbox" name="chk4" id="chk4" onclick='ajouter_user(this.id)'>Fourth</li>
				<li><input type="checkbox" name="chk5" id="chk5" onclick='ajouter_user(this.id)'>Fifth</li>
				<li><input type="checkbox" name="chk6" id="chk6" onclick='ajouter_user(this.id)'>Sixth</li>
				<li><input type="checkbox" name="chk7" id="chk7" onclick='ajouter_user(this.id)'>Seventh</li>
	  
				</ul>
				
			-->

	<br/>
	<br/>

<!---------------------------------------------------------->	
<?php			
    include('include_pied_page.php');
	include('include_publicite.php');
?>
<!---------------------------------------------------------->	
			</div>  <!-- contenu -->
<!---------------------------------------------------------->	
	</div>   <!-- main -->
<!---------------------------------------------------------->	
	<script type="text/javascript">
	////call_update()
	</script>

	<script type="text/javascript">
	////	callUpdateChat() 
    </script>

</body>
</html>
