/**
 *  ChatMain.js : 
 *	Contains all of the front-end code for the chat client.
 *	By Tristan Leonard, programmed originally for use on www.theblowmedown.com
 *	This code, or portions of it, are free to use in any project as long as some
 *	mention of the source is made. My explicit consent is not necessary, but if 
 *	you like you may let me know that my code is being utilized and, hopefully, 
 *	improved upon! My e-mail address is trisco2001@gmail.com.
 */

var xmlHttp;
var usersRequest;
var lastMessage;
var userName;
var emailAddress;
var isScrolled = false;

// The screen will attempt to be updated every X seconds.
setInterval(UpdateLayout, 3000); 
setTimeout(function()
{
    window.scrollTo(0, 1);
}, 100); 


/// Shortcut method for document.getElementById. 
// Saw this idea on the net somewhere, but you can 
// define a function by a dollar sign to do something.
// Henceforce, in the Javascript code, the complicated
// document.getElementById call that gets a control can
// be replaced by $([ControlId]);
// Replaces:
// var txtMessage = document.getElementById("txtMessage");
// txtMessage.value = "new text";
// With: 
// $("txtMessage").value = "new text";
function $(id)
{
	return document.getElementById(id);
}

// Invokes an update of the layout.
function UpdateLayout()
{		
	var txtEmail = document.getElementById("txtEmail");
	if (txtEmail.value != "[Email Address]" && txtEmail.value != "")
	{
		var email = txtEmail.value;
	
		var pageLoader = new XMLHttpRequest();
		pageLoader.onreadystatechange = function(){
			// Do Nothing
		};	
		pageLoader.open("POST", "chat/logemailpresent.php?E=" + email, true);
		pageLoader.setRequestHeader("Content-Length", 0);
		pageLoader.setRequestHeader("EmailPosted", email);
		pageLoader.send(null);
	}
	xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = CoversationLoaded;	
	xmlHttp.open("GET", "chat/getRecentConvo.php", true);
	xmlHttp.setRequestHeader("Content-Length", 0);
	xmlHttp.send(null);

	usersRequest = new XMLHttpRequest();
	usersRequest.onreadystatechange = UsersLoaded;
	usersRequest.open("GET", "chat/getCurrentUsers.php", true);
	usersRequest.setRequestHeader("Content-Length", 0);
	usersRequest.send(null);	
	if (!isScrolled)
	{
	setTimeout(function()
	{
	    window.scrollTo(0, 1);
		isScrolled = true;
	}, 100); 
	}

	//TextChanged_EmailBox();
}

function UsersLoaded()
{
	if (usersRequest == null)
		return;

	if (usersRequest.readyState == 4 && usersRequest.status == 200)
	{
		var lblUsers = document.getElementById("userpics");
		lblUsers.innerHTML = usersRequest.responseText;
	}
}

// The conversation was loaded and is ready to populate
// only when the request's ready state is equal to 4.
function CoversationLoaded()
{
	if (xmlHttp == null)
		return;

//	return;

	if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
	{
		var lblMessage = document.getElementById("conversation");
		lblMessage.innerHTML = xmlHttp.responseText;
		
		var typingMessage = "<br><img src=\"typing.png\">";
		if (xmlHttp.responseText.indexOf("#SUM1ISTALKING#") != -1)
		{
			var lblTypeStatus = document.getElementById("typestatus");
			if (lblTypeStatus != null)
			{
			if (lblTypeStatus.innerHTML != typingMessage)
				lblTypeStatus.innerHTML = typingMessage;
			}
		}
		else
		{
			var lblTypeStatus = document.getElementById("typestatus");
			if (lblTypeStatus != null)
				lblTypeStatus.innerHTML = "";
		}
	
	}
}

function KeyPress_TextBox(e)
{
	var characterCode;

	// No idea what this is for; something about 
	// IE vs Mozilla differences.
	if(e && e.which){
		e = e;
		characterCode = e.which;
	}
	else{
		e = event;
		characterCode = e.keyCode;
	}
	
	// If the character passed is 13 (Carriage Return) 
	// or 10 (Enter), click the send button.
	if (characterCode == 13 || characterCode == 10)
	{
		Click_SendButton();
		return;
	}
		
	xmlHttp = new XMLHttpRequest();
	xmlHttp = setRequestHeader("Content-Length", 0);
	xmlHttp.onreadystatechange = function(){
		// Do Nothing
	};	
	xmlHttp.open("POST", "chat/logtype.php", true);
	xmlHttp.send(null);
}

function Click_SendButton()
{
	try
	{
		// This chat only works for Safari, Firefox, Opera 
		// and only the latest version of Internet Explorer. 
		// Go Microsoft. 
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// You could try to declare xmlHttp as a new ActiveX 
		// version of the control here, but meh.
		alert("This browser is certainly not an iPhone.");
	}
	
	// When the message gets posted, call postMessage. 
	// In Javascript, function pointers are super easy!
	xmlHttp.onreadystatechange = MessagePosted;	
	
	// We're going to open the postMessage.php file and run it.
	// POST isn't quite relevant until I figure out how to set 
	// POST variables from here. 
	xmlHttp.open("POST", "chat/postMessage.php", true);
	
	// Set Request Header will add an additional variable to the 
	// SERVER variable, and will take the format of 
	// $_SERVER['HTTP_NEWMESSAGE'] here.
	xmlHttp.setRequestHeader("NewMessage", "X" + lastMessage);
	xmlHttp.setRequestHeader("UserName", userName);
	xmlHttp.setRequestHeader("EmailAddress", emailAddress);
	xmlHttp.setRequestHeader("Content-Length", 0);
	
	// Sends off the request! Wheee!
	xmlHttp.send(null);
}

/// This method is invoked twice for step 1, then once for 2, 3, and 4 each.
function MessagePosted()
{
	// The request has changed its state, but it may not be finished.
	// Regardless, we can change the text box's value to empty string. 
	var txtMessage = document.getElementById("txtMessage");
	var txtEmail = document.getElementById("txtEmail");
	var txtName = document.getElementById("txtName");
	
	// Wait a minute... we set the lastMessage variable once we've posted?
	// There are two invokes of this method where the ready 
	// state is 1. One for the open, and one more after. The second one must
	// occur after the setRequestHeader, otherwise all messages would be "" 
	// because of what happened on the lines below this comment. 
	lastMessage = txtMessage.value;
	
	// The email address defines the unique client, and each client is given 
	// a unique color code in the database to use for their name. The e-mail 
	// address is not currently displayed.
	if (txtEmail.value != "[Email Address]" && txtEmail.value != "")
			emailAddress = txtEmail.value; 
	else	emailAddress = "Anonymous";
	
	if (txtName.value != "[Name]" && txtName.value != "")
			userName = txtName.value;
	else	userName = "Someone";
	
	
	// Reset the message textbox to empty.
	//if (xmlHttp.readyState == 4)
	//{
		txtMessage.value = "";
		txtMessage.focus();
	//}
}

function TextChanged_EmailBox()
{

//	txtEmail.value = "Woot";
}

function Focus_NameBox()
{
	var txtName = document.getElementById("txtName");
	if (txtName.value == "[Name]")
		txtName.value = "";
	
	var txtEmail = document.getElementById("txtEmail");
	if (txtEmail.value == "")
		txtEmail.value = "[Email Address]";
		
}

function Focus_EmailBox()
{
	var txtEmail = document.getElementById("txtEmail");
	if (txtEmail.value == "[Email Address]")
		txtEmail.value = "";
	
	var txtName = document.getElementById("txtName");
	if (txtName.value == "")
		txtName.value = "[Name]";
}

function Focus_MessageBox()
{
	var txtName = document.getElementById("txtName");
	if (txtName.value == "")
		txtName.value = "[Name]";
		
	var txtEmail = document.getElementById("txtEmail");
	if (txtEmail.value == "")
		txtEmail.value = "[Email Address]";
}

function Click_AddBookmark()
{
	var txtName = document.getElementById("txtName");
	var myName = null;
	var myEmail = null;
	
	if (txtName.value != "" && txtName.value != "[Name]")
		myName = txtName.value;
		
	var txtEmail = document.getElementById("txtEmail");
	if (txtEmail.value != "" && txtEmail.value != "[Email Address]")
		myEmail = txtEmail.value;
	
	var newurl = "";
	
	if (myName == null && myEmail == null)
		newurl = "http://www.theblowmedown.com/blowchat/";
	else
		newurl = "http://www.theblowmedown.com/blowchat/?n=" + myName + "&e=" + myEmail;
		
		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(document.title, newurl,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( newurl, document.title); }

}