var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
var d = new Date();
const TZ = d.getTimezoneOffset();
//Function for initializating the page.
function startChat() {
	//Set the focus to the Message Box.
	document.getElementById('txt_message').focus();
	//Start Recieving Messages.
	getChatText();
}		
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
	}
}

//Gets the current messages from the server
function getChatText() {
	if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
		receiveReq.open("GET", '/includes/php/getChat.php?chat='+document.getElementById('roomid').value+'&last=' + lastMessage+'&timezone=' + TZ +'&'+Math.random, true);
		receiveReq.onreadystatechange = handleReceiveChat; 
		receiveReq.send(null);
	}			
}
//Add a message to the chat server.
function sendChatText() {
	if(document.getElementById('txt_message').value == '') {
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", '/includes/php/getChat.php?chat='+document.getElementById('roomid').value+'&last=' + lastMessage, true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = handleSendChat; 
		var param = 'message=' + document.getElementById('txt_message').value;
		param += '&name='+document.getElementById('username').value;
		param += '&chat='+document.getElementById('roomid').value;
		sendReq.send(param);
		document.getElementById('txt_message').value = '';
	}							
}
function isValidAction(action) {
  return (action=='play'||action=='pause'||action=='stop'||action=='back1'||action=='fore1'||action=='back5'||action=='fore5');
}
//Send a video action to the chat server.
function sendAction(action) {
	if(!isValidAction(action)) {
//		alert("Incorrect action");
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", '/includes/php/getChat.php?chat='+document.getElementById('roomid').value+'&last=' + lastMessage, true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = handleSendChat; 
		var param = 'name='+document.getElementById('username').value;
		param += '&chat='+document.getElementById('roomid').value;
		param += '&action='+action;
		sendReq.send(param);
	}							
}
//When our message has been sent, update our page.
function handleSendChat() {
	//Clear out the existing timer so we don't have 
	//multiple timer instances running.
	clearInterval(mTimer);
	getChatText();
}
function handleReceiveChat() {
	if (receiveReq.readyState == 4) {
		//Get a reference to our chat container div for easy access
		var chat_div = document.getElementById('div_chat');
		//Get the AJAX response and run the JavaScript evaluation function
		//on it to turn it into a useable object.  Notice since we are passing
		//in the JSON value as a string we need to wrap it in parentheses
		var response = eval("(" + receiveReq.responseText + ")");
    if(lastMessage!=0) { //So the player doesn't run through all of the commands sent previously
		  for(i=0;i < response.messages.message.length; i++) {
  		  if(isValidAction(response.messages.message[i].action)) {
  		    handleReceiveAction(response.messages.message[i].action);
    			chat_div.innerHTML += '<p class="action">'+response.messages.message[i].user+' pressed '+response.messages.message[i].action+'</p>';
  		  } else {
          chat_div.innerHTML += '<h3 class="chat">'+response.messages.message[i].user+' <span class="chat_time">' +  response.messages.message[i].time + '</span></h3>';
    			chat_div.innerHTML += '<p class="chat">"'+response.messages.message[i].text + '"</p>';
          playBeep(); //Maybe play a beep if user is in fullscreen and has enabled it
  		  }
  			chat_div.scrollTop = chat_div.scrollHeight;
  			lastMessage = response.messages.message[i].id;
	    }
		} else {
			lastMessage = response.messages.message[response.messages.message.length-1].id;
      var i=response.messages.message.length-1;
		  if(isValidAction(response.messages.message[i].action)) {
		    handleReceiveAction(response.messages.message[i].action);
  			chat_div.innerHTML += '<p class="action">'+response.messages.message[i].user+' pressed '+response.messages.message[i].action+'</p>';
		  } else {
        chat_div.innerHTML += '<h3 class="chat">'+response.messages.message[i].user+' <span class="chat_time">' +  response.messages.message[i].time + '</span></h3>';
  			chat_div.innerHTML += '<p class="chat">"'+response.messages.message[i].text + '"</p>';
        playBeep(); //Maybe play a beep if user is in fullscreen and has enabled it
		  }
		}
		mTimer = setTimeout('getChatText();',200); //Refresh our chat in 0.2 seconds
	}
}
//This functions handles when the user presses enter.  Instead of submitting the form, we
//send a new message to the server and return false.
function blockSubmit() {
	sendChatText();
	return false;
}
//This cleans out the database so we can start a new chat session.
function resetChat() {
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", '/includes/php/getChat.php?chat='+document.getElementById('roomid').value+'&last=' + lastMessage, true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = handleResetChat; 
		var param = 'action=reset';
		sendReq.send(param);
		document.getElementById('txt_message').value = '';
	}							
}
//This function handles the response after the page has been refreshed.
function handleResetChat() {
	document.getElementById('div_chat').innerHTML = '';
	getChatText();
}