<?php
	include "library.php";

	$cxn = start_code( true );

	page_header( "", $cxn );


		/* 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")
	{
		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">

	function send_text()
	{  
		var xmlHttp;

		try
		{
			xmlHttp = new XMLHttpRequest();	/* Firefox, Opera 8.0+, Safari */
		}
		catch (e)
		{	 		/* Internet Explorer */
			try
			{
				 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 */

		var url = "save_chat_text.php?conversationid=<?php echo $conversation_id ?>&memberid=<?php echo $id1 ?>&text=" + document.getElementById( "id1" ).value;

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

	    xmlHttp.send( null );


			/* add the text to the window */

		document.getElementById( "id2" ).value = document.getElementById( "id2" ).value + "\n" + "<?php echo $handle; ?>" + ": " + document.getElementById( "id1" ).value + "\n";

		document.getElementById( "id1" ).value = "";


			/* scroll texarea to bottom */

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

	function listen_text()
	{  
		var xmlHttp;

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


		xmlHttp.onreadystatechange = 
			function()
			{
				if (xmlHttp.readyState==4)
				{
					if (xmlHttp.responseText != "")
						document.getElementById( "id2" ).value += "\n" + xmlHttp.responseText;
				}
			}


			/* send the text to the server */

		var url = "get_chat_text.php?conversationid=<?php echo $conversation_id ?>&memberid=<?php echo $id2 ?>";

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

	    xmlHttp.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);

/*
		if (event.which == 13)
		{
			event.which = 9;
			send_text();
		}
		
		if (event.keyCode==13)
		{
			event.keyCode = 9;
			send_text();
		}
*/
	}


		/* install the text listener */

	window.setInterval('listen_text()', 500);


</script>

<form name='myForm'>


<?php
		if ($new_chat == "true")
		{
			if ($sex2 == "Male")
				echo "<textarea class='chat' id='id2' rows='20' cols='80' readonly>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.\n\n</textarea><br>";
			else
				echo "<textarea class='chat' id='id2' rows='20' cols='80' readonly>A message has been send to ".$handle2." to let her know that you would like to chat with her. Please wait for her to respond.\n\n</textarea><br>";
		}
		else
			echo "<textarea class='chat' id='id2' rows='20' cols='80' readonly>Ready for chat. Please type a message.\n\n</textarea><br>";


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

?>

<br>

<input class='chat' type='text' id='id1' size='95' onKeyPress='return catch_enter_key(event)'>

<input type='button' onclick='send_text()' value='send' onfocus='document.getElementById( "id1" ).focus()'>

</form>
</body>
</html>

