//Technical Research on Internet Token Operational Node//
var lastID = 0; //initial value will be replaced by the latest known id
var channel = '#general'; //initial channel name to post to
var myfocus = '';
var lastBufferItem = '';
var onFlood = false;

function initChatEngine() {
	addevent('[006] TRITON AJAX2 COMPONENT');
	document.getElementById('chatbarText').focus(); //document.forms['chatForm'].elements['chatbarText'].focus();
	document.getElementById('chatbarText').setAttribute('autocomplete','off'); //document.forms['chatForm'].elements['chatbarText'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
	addevent('[010] ACTIVATING STATUS');
	checkStatus('active'); //sets the initial value and state of the input comment
	addevent('[012] INT. CHAT DATA RECEPTION');
	receiveChatText();
	document.getElementById('chatContentDivWindow').innerHTML = "Triton2 Chat Component Ready";
}

function playSound(sound) {
	//if (myfocus == 'blured') {
		// out of focus... //
	//	if (document.beep.beeponmsg.checked == true) {
	//		document.getElementById('ChatSoundDiv').innerHTML = "<embed src='images/sounds/" + sound + ".wav' hidden=true autostart=true loop=false>";
	//	}
	//}
}

//initiates the first data query
function receiveChatText() {
	addevent('[020] INIT. CONTENT RECEPTION');
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
  		addevent('[022] CONNECTING TO DATABASE');
		httpReceiveChat.open("GET", 'pages/chat/getChatData.php?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000), true);
    	httpReceiveChat.onreadystatechange = handleHttpReceiveChat; 
  		addevent('[025] SOCKET STATE CHANGED');
		httpReceiveChat.send(null);
	}
	
	//insertEchoText(typeof rxtimer); 
	if (typeof rxtimer == 'number') {
		clearTimeout(rxtimer);
		addevent('[030] TIMER KILLED');
	}
	rxtimer = setTimeout('receiveChatText();',7000);
}

//deals with the servers' reply to requesting new content
function handleHttpReceiveChat() {
  if (httpReceiveChat.readyState == 4) {
    addevent('[033] RECEIVING DATA');
	results = httpReceiveChat.responseText.split('---'); // the fields are seperated by ---
    if (results.length > 2) {
		for(i=0;i < (results.length-1);i=i+3) { // goes through the result one message at a time
			addevent('[037] INIT DATA MERGE');
			if (results[i+1] == 'SYSTEM') {
				addevent('[039] SYSTEM TEXT');
				insertSystemText(results[i+2]); // Insert system text //
				rtop = setTimeout('receiveTopic();',1000);
			}
			else if (results[i+1] == 'ECHO') {
				addevent('[039] LOCALECHO TEXT');
				insertEchoText(results[i+2]); // Insert echo text //
			}
			else if (results[i+1] == 'WALLOPS') {
				addevent('[039] WALLOPS TEXT');
				insertWallOps(results[i+2]); // Insert echo text //
			}
			else if (results[i+1] == 'ACTION') {
				addevent('[039] ACTION TEXT');
				insertActionText(results[i+2]); // Insert echo text //
			}
			else if (results[i+1] == 'MSG') {
				addevent('[039] PRIVATE TEXT');
				insertMsgText(results[i+2]); // Insert echo text //
			}
			else if (results[i+1] == 'SOUND') {
				addevent('[039] SOUND');
				insertSound(results[i+2]); // Insert echo text //
			} 
			else if (results[i+1] == 'SHARE') {
				addevent('[039] SHARE');
				insertShare(results[i+2]); // Insert echo text //
			} 
			else {
				addevent('[042] CHANNEL MESSAGE');
				insertNewContent(results[i+1],results[i+2]); // inserts the new content into the page
			}
		}
		lastID = results[results.length-4];
	}
  }
  scrollDown(); // Scroll the chat window down //
}




////////////////////////////////////// TOPIC HANDLING ////////////////////////////////////////////
function receiveTopic() {
	addevent('[087] REQ. CHANS LIST');
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
		addevent('[089] OPENNING STREAM SOCKET');
		httpReceiveChat.open("GET", 'pages/chat/GetTopics.php', true);
    	httpReceiveChat.onreadystatechange = handleTopic; 
  		addevent('[092] SOCKET STATE CHANGED');
		httpReceiveChat.send(null);
		setTimeout('receiveNicks()',1000);
	}
}

function handleTopic() {
	addevent('[102] RECEIVING TOPIC');
	if (httpReceiveChat.readyState == 4) {
		var thetopic = httpReceiveChat.responseText;
		topsplit = thetopic.split(' ');
		
		var channame = topsplit[1].substr(topsplit[1].indexOf("#"));
		var chancount = topsplit[2].substring(1,topsplit[2].indexOf("]"));
		document.getElementById('ChannelName').innerHTML = '<span class=topiccontent>' + channame + '</span>';
		
		document.getElementById('ChannelCount').innerHTML = '<span class=topiccontent>' + chancount + '</span>';
		
		document.getElementById('topic').innerHTML = thetopic;
	}
}
///////////////////////// END OF CHANS /////////////////////////////////

////////////////////////////////////// NICKS HANDLING ////////////////////////////////////////////
function receiveNicks() {
	//addevent('[087] REQ. NICKS LIST');
	//if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
	//	addevent('[089] OPENNING STREAM SOCKET');
	//	httpReceiveChat.open("GET", 'pages/chat/GetNicknames.php', true);
    //	httpReceiveChat.onreadystatechange = handleNicks
  	//	addevent('[092] SOCKET STATE CHANGED');
	//	httpReceiveChat.send(null);
	//	setTimeout('receiveChans();',1000);
	receiveNickNamesData();
	//}
}

function handleNicks() {
	addevent('[102] RECEIVING NICKS');
	if (httpReceiveChat.readyState == 4) {
		document.getElementById('nicklist').innerHTML = httpReceiveChat.responseText; //set results as response text
	}
}
///////////////////////// END OF NICKS /////////////////////////////////

////////////////////////////////////// CHANS HANDLING ////////////////////////////////////////////
function receiveChans() {
//	addevent('[087] REQ. CHANS LIST');
//	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
//		addevent('[089] OPENNING STREAM SOCKET');
//		httpReceiveChat.open("GET", 'pages/chat/getchans2.php', true);
//    	httpReceiveChat.onreadystatechange = handleChans
//  		addevent('[092] SOCKET STATE CHANGED');
//		httpReceiveChat.send(null);
//	}
}

function handleChans() {
//	addevent('[102] RECEIVING CHANS');
//	if (httpReceiveChat.readyState == 4) {
//		document.getElementById('chanlist').innerHTML = httpReceiveChat.responseText; //set results as response text
//	}
}
///////////////////////// END OF CHANS /////////////////////////////////


//inserts the new content into the page
function insertNewContent(liName,liText) {
	addevent('[089] APPENDING CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	HiCheck = liText.split('.!.');
	if (HiCheck[0] == "hilight") { // Hilighted content...
		content.innerHTML = content.innerHTML.substring(content.innerHTML.length-9000, content.innerHTML.length) + '<br><span class=nick>'+liName+':</span> &nbsp;<span class=hilighttext>' + HiCheck[1] + '</span>';
	} else if (HiCheck[0] == "mytext") { // mytext
		content.innerHTML = content.innerHTML.substring(content.innerHTML.length-9000, content.innerHTML.length) + '<br><span class=nick>'+liName+':</span> &nbsp;<span class=mytext>' + HiCheck[1] + '</span>';
	} else { // Normal text //
		content.innerHTML = content.innerHTML.substring(content.innerHTML.length-9000, content.innerHTML.length) + '<br><span class=nick>'+liName+':</span> &nbsp;<span class=text>' + liText + '</span>';
	}
}


function insertSystemText(theText) {
	addevent('[095] APPENDING SYS CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	content.innerHTML = content.innerHTML + '<br><span class=system>## ' + theText + '</span>';
}

function insertSound(theSound) {
	addevent('[095] APPENDING SYS CONTENT');
	document.getElementById('ChatSoundDiv').innerHTML = "<embed src='" + theSound + "' hidden=true autostart=true loop=false>";
}

function insertShare(content) {
	addevent('[095] APPENDING SHR CONTENT');
	CntHash = content.split('~~');
	document.getElementById('PicShare').innerHTML = CntHash[0] + " shared that picture with you:<br><img src=\"userfiles/temp/" + CntHash[1] + "\" height=300><br><a href=# onClick=\"document.getElementById('PicShare').style.visibility='hidden';\">Close</a>";
	document.getElementById('PicShare').style.visibility = 'visible';
}


function insertWallOps(theText) {
	addevent('[095] APPENDING WOP CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	content.innerHTML = content.innerHTML + '<br><span class=wallops>## ' + theText + '</span>';
}

function insertActionText(theText) {
	addevent('[095] APPENDING ACT CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	content.innerHTML = content.innerHTML + '<br><span class=action>## ' + theText + '</span>';
}

function insertEchoText(theText) {
	addevent('[095] APPENDING ECHO CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	content.innerHTML = content.innerHTML + '<br><span class=echo>## ' + theText + '</span>';
}

function insertMsgText(theText) {
	addevent('[095] APPENDING MSG CONTENT');
	var content = document.getElementById('chatContentDivWindow');
	content.innerHTML = content.innerHTML + '<br><span class=privatemsg>Whisper: ' + theText + '</span>';
}

function goToBuffer() {
	document.getElementById('chatbarText').value = lastBufferItem; //document.forms['chatForm'].elements['chatbarText'].value = lastBufferItem;
	addevent('[212] Buffer rollback');
}

function ClearChatBuffer() {
	document.getElementById('chatbarText').value = ''; //document.forms['chatForm'].elements['chatbarText'].value = ''
	addevent('[216] Buffer rollup');
}

//stores a new comment on the server
function sendComment() {
	if (!onFlood) {
		
		onFlood = true;
		
		document.getElementById('chatbarText').focus(); 
		addevent('[103] RECEIVED USER DATA');
		currentChatText = document.getElementById('chatbarText').value; //document.forms['chatForm'].elements['chatbarText'].value;
		if (currentChatText != "") {
			lastBufferItem = currentChatText;
		}
		
		// REPLACE BOGGUS CHARACTERS //
		currentChatText = currentChatText.replace(/\+/gi, "~!~and~!~#43;");
		currentChatText = currentChatText.replace(/\&/gi, "~!~and~!~");
		//
		
		channel = document.getElementById('channel').value; //document.forms['chatForm'].elements['channel'].value;
		//if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
		if (httpSendChat.readyState == 4 || httpSendChat.readyState == 0) {
			addevent('[107] SOCKET READY');
			param = 'channel=' + channel + '&c=' + currentChatText;	
			addevent('[110] OPENNING CONNECTION');
			
			//if (document.forms['chatForm'].elements['chatbarText'].value == lastBufferItem) {
			document.getElementById('chatbarText').value = ''; //document.forms['chatForm'].elements['chatbarText'].value = '';
			document.getElementById('chatbarText').focus(); 
			//}
			
			httpSendChat.open("POST", 'pages/chat/sendChatData.php', true);
			httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			httpSendChat.onreadystatechange = handleHttpSendChat;
			httpSendChat.send(param);
			addevent('[115] DATA SENT');
			//document.forms['chatForm'].elements['chatbarText'].value = '';
		} else {
			addevent('[193] SOCKET BUSY - SLEEP');
			setTimeout('sendComment();',300);
		}
	
		setTimeout('onFlood=false',1000);
	
	} else { 
		addevent('[272] FLOOD DELAYED');
		setTimeout('sendComment();',500);
	}
		
}


//deals with the servers' reply to sending a comment
function handleHttpSendChat() {
  if (httpSendChat.readyState == 4) {
  	addevent('[126] REFRESHING CHAT DATA');
	receiveChatText(); //refreshes the chat after a new comment has been added (this makes it more responsive)
  }
}

function scrollDown() {
 content = document.getElementById('chatContentDivWindow');
 content.scrollTop = content.scrollHeight;

	// New scroller //
	//var top = document.getElementById('chatContentDivWindow');
	//scrollbar.swapContent(top);
	//if (top.y) scrollbar.scrollTo(0, top.y);

}


function checkStatus(focusState) {
	if (focusState == 'active') {
		myfocus = 'focused';
	} else {
		myfocus = 'blured';
	}
}


function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}


var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();


// LOGS AND STATUS WINDOW //
function addevent(texttoprint) {
	document.getElementById('status').innerHTML = '<table width=100% height=100%><tr><td valign=middle class=statusdiv>'+texttoprint+'</td></tr></table>';
}
