<?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']);		
			}	
/************************************************************************/	

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

			for($i = 0; $i < 9; $i++)
			{
				$val = $associative[$icons[$i]];
				$str = str_replace($icons[$i], $val , $str);
			}
				
			return($str);
}
								
?>			

<!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');
?> 

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<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>

	// si on ferme l'onglet ou le navigateur alors il faut remettre à jour la table des utilisateurs online
window.onbeforeunload = function()
{
			$.ajax({
					type: "POST",
					url: "update_user_status.php"
			});
}

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 notification()
{

            var xhr = getXhr()
			// On défini ce qu'on va faire quand on aura la réponse
			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;
						
						if(retour == 1)
						{  	
							//alert("retour");
							var beepfile = 'beep1.wav'; 
							document.getElementById('chatbeep').innerHTML= '<audio autoplay="autoplay" src="'+beepfile+'" type="audio/wav"><embed src="'+beepfile+'" hidden="true" autostart="true" loop="false" /></audio>';


						}
					}
			}
            
			xhr.open("GET","notification.php",true);
			xhr.send(null);
}

function mise_a_jour()
{
			notification(); 
			setTimeout("mise_a_jour()", 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);
}

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;
											$txt = 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
				$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);
			
				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>
				
				
				<p id="chatbeep"></p>
				
				<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>
					
				</div> 
	
	</div>		
	
<?php
			date_default_timezone_set('Europe/Paris');
			$ts_actuel = strtotime(date("d-m-Y H:i:s"));
			echo $ts_actuel;
			$date = date('d/m/Y H:i:s', $ts_actuel);
			echo $date;
//			$temps = 365*24*3600; // jour * heure * secondes
//			setcookie ("pseudo", $_POST['nom'], time() + $temps);
//		    $iCookieTime = time() + 24*60*60*30;
//	        setcookie("member_name", $sName, $iCookieTime, '/');
//	        $_COOKIE['member_name'] = $sName;
//			setCookie(name, value, expire). 
?>					

			<br/>
			<br/>

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

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

</body>
</html>
