<?php
	include "library.php";

	$cxn = start_code( true );

	$cxn_common = db_common_login();


	page_header( "", $cxn, $cxn_common );


		/* get parameters */

	$id1 = val( $_GET, 'id1' );

	$id2 = val( $_GET, 'id2' );

	$conversation_id = val( $_GET, 'conversationid' );

	$new_chat = val( $_GET, 'newchat' );

	$returnpoint = val( $_SESSION, "returnpoint" );

	$startpos = val( $_SESSION, "startpos" );


		/* check them */

	crash_if_missing( $id1, "id1 missing in chat", $cxn );

	crash_if_missing( $id2, "id2 missing in chat", $cxn );

	crash_if_missing( $new_chat, "new_chat missing in chat", $cxn );

	if ($new_chat == "false")
		crash_if_missing( $conversation_id, "conversation_id missing in chat", $cxn );

	crash_if_missing( $returnpoint, "return point missing in chat", $cxn );


		/* cancelled by user */

	if (val( $_GET, "chat" ) == "no")
	{
		echo black( "Chat request cancelled<br><br>" );

		show_return_point( $returnpoint, $startpos, $id2 );

		exit();
	}

		/* get our own handle */

	$query = "SELECT handle FROM profile WHERE id = ".$id1;

	$result = run_query( $query, $cxn );

	$data = get_row( $result );

	$handle = $data['handle'];


		/* get other person's handle */

	$query = "SELECT handle, sex FROM profile WHERE id = ".$id2;

	$result = run_query( $query, $cxn );

	$data = get_row( $result );

	$handle2 = $data['handle'];
	$sex2 = $data['sex'];


		/* start a conversation */

	if ($new_chat == "true")
	{

//		alert( "Chat added" );
		
		if (query_has_rows( "SELECT id FROM active_chats WHERE initiator_id = ".$id1." AND responder_id = ".$id2, $cxn ))
			run_query( "UPDATE active_chats SET notified = 'no' WHERE initiator_id = ".$id1." AND responder_id = ".$id2, $cxn );
		else
			run_query( "INSERT INTO active_chats (initiator_id, responder_id, notified) VALUES (".$id1.", ".$id2.", 'no' )", $cxn );

		$query = "SELECT id FROM active_chats WHERE initiator_id = ".$id1." AND responder_id = ".$id2;

		$result = run_query( $query, $cxn );

		$data = get_row( $result );

		$conversation_id = $data['id'];

		$started = date("Y-m-d H:i:s");

		$query = "INSERT INTO chat_history (conversation_id, initiator_id, responder_id, started) values (".$conversation_id.", ".$id1.", ".$id2.", '".$started."')";

		$result = run_query( $query, $cxn );
		
	}
	else	/* accept a chat request */
	{
		$sent = date("Y-m-d H:i:s");

		$query = "INSERT INTO message (sender_id, receiver_id, type, sent, show_in_inbox) values (".$id2.", ".$id1.", 'chat', '".$sent."', 'no' )";

		$result = run_query( $query, $cxn );

//		$started = date("Y-m-d H:i:s");
//		$query = "INSERT INTO chat_history (conversation_id, initiator_id, responder_id, started) values (".$conversation_id.", ".$id2.", ".$id1.", '".$started."')";
//		$result = run_query( $query, $cxn );
	}

?>

<script type="text/javascript">

		var xmlHttp;

	function send_text()
	{  
//		var xmlHttp;

		try
		{
			xmlHttp = new XMLHttpRequest();	/* Firefox, Opera 8.0+, Safari */
		}
		catch (e)
		{	 		/* Internet Explorer */
			try
			{
				 xmlHttp = new XDomainRequest();
				 
//				 xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');				 
			}
			catch (e)
			{
    
				try
				{
					xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
				}
				catch (e)
				{
					/* alert( 'Your browser does not support AJAX!' ); */
					return false;
				}	   
			}	 
		}

			/* send the text to the server */
			
		    // have to use POST in this function instead of GET as Internet Explorer 11 caches the results of AJAX queries instead of re-sending them
		    
		var url = "save_chat_text.php?conversationid=<?php echo $conversation_id ?>&memberid=<?php echo $id1 ?>&text=" + document.getElementById( "id1" ).value;

	    xmlHttp.open( "POST", url, true );

	    xmlHttp.send( null );


			/* add the text to the window */


		document.getElementById( "id3" ).innerHTML = document.getElementById( "id3" ).innerHTML + "<span class='chat'><?php echo $handle; ?>" + ": " + document.getElementById( "id1" ).value + "</span><br><br>";
						
		document.getElementById( "id1" ).value = "";


			/* scroll texarea to bottom */

//		document.getElementById( "id2" ).scrollTop = document.getElementById( "id2" ).scrollHeight - document.getElementById( "id2" ).clientHeight;
		
		document.getElementById( "id3" ).scrollTop = document.getElementById( "id3" ).scrollHeight;
	}

/*	var xmlHttp2;  didn't work in firefox*/


	function listen_text()
	{

		var xmlHttp2;

		try
		{
			xmlHttp2 = new XMLHttpRequest();	/* Firefox, Opera 8.0+, Safari */
		}
		catch (e)
		{	 		/* Internet Explorer */
			try
			{
				 xmlHttp2 = new ActiveXObject('Msxml2.XMLHTTP');
			}
			catch (e)
			{
				try
				{
					xmlHttp2 = new ActiveXObject('Microsoft.XMLHTTP');
				}
				catch (e)
				{
					/* alert( 'Your browser does not support AJAX!' ); */
					return false;
				}	   
			}	 
		}


		xmlHttp2.onreadystatechange =
			function()
			{
				if (xmlHttp2.readyState==4)
				{
					if (xmlHttp2.responseText != "")
					{
//						document.getElementById( "id2" ).value += "\n" + xmlHttp2.responseText;
						
						document.getElementById( "id3" ).innerHTML = document.getElementById( "id3" ).innerHTML + "<span class='chat2'>" + xmlHttp2.responseText + "</span>";
						
						document.getElementById( "id3" ).scrollTop = document.getElementById( "id3" ).scrollHeight;						
					}
				}
			}


			/* send the text to the server */
			
		    // have to use POST in this function instead of GET as Internet Explorer 11 caches the results of AJAX queries instead of re-sending them
		    
		var url = "get_chat_text.php?conversationid=<?php echo $conversation_id ?>&memberid=<?php echo $id2 ?>";

	    xmlHttp2.open( "POST", url, true );

	    xmlHttp2.send( null );
	}


		/* send a line of text when the user presses enter */

	function catch_enter_key( evt )
	{
		var keyCode;

		keyCode = evt.keyCode || evt.which;

		if (keyCode == 13)
		{
			send_text();
			return (false);
		}

		return (true);

	}


		/* install the text listener */
		
							// **NOTE** don't set this value to too low a value or the window don't seem to update
							// it is especially slow in Africa
							
	window.setInterval('listen_text()', 1600);


</script>


<form name='myForm'>


<?php
		if ($new_chat == "true")
		{
			$id2 = val( $_GET, 'id2' );		
			
			echo "<br>";
			
			show_photo( $id2, 100, -1, true, false, $cxn );		
			
			echo "<br><br>";
		
			echo red("<i>Some members do not respond to chat requests.</i><br><br>" );

			if (! low_res_screen())						
			{				
				if ($sex2 == "Male")
					echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 500px; width: 600px;'>A message has been send to ".$handle2." to let him know that you would like to chat with him. Please wait for him to respond.<br><br></div><br>";
				else
					echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 500px; width: 600px;'>A message has been send to ".$handle2." to let her know that you would like to chat with him. Please wait for him to respond.<br><br></div><br>";
			}
			else
			{				
				if ($sex2 == "Male")
					echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 350px; width: 250px;'>A message has been send to ".$handle2." to let him know that you would like to chat with him. Please wait for him to respond.<br><br></div><br>";
				else
					echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 350px; width: 250px;'>A message has been send to ".$handle2." to let her know that you would like to chat with him. Please wait for him to respond.<br><br></div><br>";
			}
				
		}
		else
		{
			$id2 = val( $_GET, 'id2' );		
			
			echo "<br>";
			
			show_photo( $id2, 100, -1, true, false, $cxn );		
			
			echo "<br><br>";

			echo red("<i>Some members do not respond to chat requests.</i><br><br>" );

			if (! low_res_screen())						
				echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 500px; width: 600px;'>Ready for chat. Please type a message.<br><br></div><br>";
			else
				echo "<div id='id3' style='overflow: auto; border: solid 1px; height: 350px; width: 250px;'>Ready for chat. Please type a message.<br><br></div><br>";			
		}

/*<input type='text' id='id1' size='95' onkeydown='if(event.keyCode==13) {event.keyCode = 9; send_text()};'>*/



	echo "<br>";

	if (! low_res_screen())
		echo "<input class='chat' autofocus type='text' id='id1' size='95' style='background-color: lightyellow' onKeyPress='return catch_enter_key(event)'>";
	else
		echo "<input class='chat' autofocus type='text' id='id1' size='30' style='background-color: lightyellow' onKeyPress='return catch_enter_key(event)'>";
		
		
	echo "<input type='button' onclick='send_text()' value='send' onfocus='document.getElementById( 'id1' ).focus()'>";

	echo "</form>";

	echo "<br><br>";

	echo show_home_link();
	
	echo "</body>";

	echo "</html>";

?>