//Global variables
var myWidth = 0;
var myHeight = 0;
var timeID;
var refreshRate = 880; // 500ms
var rnd = Math.random();
var isFirefox;
var isIE;
var dontScroll = false;
var isSendingCommand = false;
var szStoredBufferToSend = "";
var plExit = false;

//var XmlHttp;
var AjaxServerPageName;
AjaxServerPageName = "Server.aspx";

//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable  
function getAjax()
{
	var XmlHttp;
	
	//Creating object of XMLHTTP in IE
	try
	{
		XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttp = null;
		}
	}
	//Creating object of XMLHTTP in Mozilla and Safari 
	if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttp = new XMLHttpRequest();
	}
	return XmlHttp;
}

// Get browser type
function sniffBrowserType() {
	isFirefox = ( navigator.appName == "Netscape" );
	isIE = (navigator.appName == "Microsoft Internet Explorer" ); 
}

function getEchoStatus()
{
	var chk = document.getElementById( "echoCheck" );
	if (chk != null)
	{
		if (chk.value == "on") { return true; }
	}
	return false;
}

function setEchoStatus(str)
{
	var chk = document.getElementById( "echoCheck" );
	if (chk != null)
	{
		chk.value = str;
		if (str == "on") {chk.checked="checked";} else {chk.checked="";}
	}
	return true;
}

function handleIncomingReq(s)
{
	if (s == null || s == "") return;
	var idata = s.indexOf("||", 0);
	if (idata != -1)
	{
		var txtar = document.getElementById("textar");
		txtar.innerText = s;
		window.document.title="Incoming " + s.substr(2, 1) + rnd;
		return;
	}
	var iprmpt = s.indexOf("|PROMPT", 0);
	var iprmptEnd = s.indexOf("|ENDPROMPT", 0);
	if (iprmpt != -1 && iprmptEnd != -1)
	{				
		var iLenPrompt = (iprmptEnd - iprmpt) - 7;
		var oo = document.getElementById( "statusprompt" );					
		if (oo != null)
		{				
//			var sprompt = s.substr(iprmpt + 7, iLenPrompt);
//			var cnm = sprompt.indexOf(">", 0);
//			var cnme = sprompt.indexOf("<", cnm);
//			var chrnm = sprompt.substr(cnm+1, cnme-cnm);
//			var ostatwin = null;
//			if ( window.frames != null ) {
//			 for ( i = 0; i< window.frames.length; i++ ) {
//				if (window.frames(i).name == "QuickStats") {
//					ostatwin = window.frames(i);
//				}
//			 }
//			}
//			
			/* if (ostatwin != null) {
				var txtNm = getElementOfWindow(ostatwin, "txtCharName");
				txtNm.value = chrnm;
			} else {
				var w = window.open('QuickStats.htm','QuickStats','location=0,menubar=0,status=0,toolbar=0,height=150,left=0,top=0,width=200,directories=0',false);
				var txtt = getElementOfWindow(w, "txtCharName");
				alert(txtt.toString());
				if (txtt != null)
				{
					txtt.value = chrnm;
				}				
			} */
			// oo.innerHTML = sprompt;
		}
		
		if (iprmpt == 0) {s = s.substr(7);} 
		else { s = s.substr(0, iprmpt) + s.substr(iprmptEnd+10);	}
	}
	if (s.indexOf("|CLRS", 0) != -1) {
		//obj = document.getElementById( "chatbuffer" );			
		//obj.innerHTML = "<span> </span>";	
		s = s.substr(5);		
	}
	if (s.indexOf("|QUIT", 0) != -1) {
		s = "<br/>You've left the game.<br/>";
		setEchoStatus("off");
		plExit = true;
		window.clearTimeout( timeID );
	} else {
		if (s.indexOf("|EOFF", 0) != -1)
		{
			var userMessageElement = document.getElementById("mytext");
			if (userMessageElement == null) alert("CRAP");
			userMessageElement.style.color = "black";			
			s = s.substr(5);
			setEchoStatus("off");
		} else if (s.indexOf("|EON", 0) != -1) {
			var userMessageElement = document.getElementById("mytext");
			if (userMessageElement == null) alert("CRAP");
			userMessageElement.style.color = "white";				
			s = s.substr(4);
			setEchoStatus("on");
		}
		if (s.indexOf("|EPON", 0) != -1) {
			var userMessageElement = document.getElementById("mytext");
			if (userMessageElement == null) alert("CRAP");
			userMessageElement.style.color = "white";				
			s = s.substr(5);
			setEchoStatus("off");
		}	
		if (s != null && s != "") {
			obj = document.getElementById( "chatbuffer" );			
			if (obj == null) alert("REAL CRAP");
			obj.insertAdjacentHTML("beforeEnd", s);
			scrollChatPane();
		}
	}
}

// Capture the enter key on the input box and post message
function captureReturn( event )
{
	if(event.which || event.keyCode)
	{
		if ((event.which == 13) || (event.keyCode == 13)) 
		{
			postText();
			return false;
		}
		else if ((event.which == 38) || (event.keyCode == 38))
		{
			displayLastCommand();
			return false;
		}
		else if ((event.which == 40) || (event.keyCode == 40))
		{
			displayNextCommand();
			return false;
		}
		else if ((event.which == 8) || (event.keyCode == 8))
		{
				var tb = document.getElementById( "mytext" );
				if (tb.value == null) return false;
				if (tb.value == "") return false;			
				obj = document.getElementById( "chatbuffer" );
				if (obj == null) return false;
				var c = String.fromCharCode(event.keyCode);
				if (obj.innerHTML.length > 0)
				{
					obj.innerHTML = obj.innerHTML.substr(0, obj.innerHTML.length - 1);
				}
				return false;
		} else if ((event.which == 32) || (event.keyCode == 32))
		{
			if (getEchoStatus() == true)
			{
				obj = document.getElementById( "chatbuffer" );
				if (obj != null)
					obj.insertAdjacentHTML("beforeEnd", "&nbsp;");
			}
			var tb = document.getElementById( "mytext" );
			if (tb == null) return false;
			// tb.value = selstart
			return false;
		}
		else {
		// 8 is backspace, 46 is delete
			if (getEchoStatus() == true)
			{
				obj = document.getElementById( "chatbuffer" );				
				var c = event.keyCode;
				if (c >= 65 && c <= 90 && event.shiftKey == false && event.shiftLeft == false)
				{
					c = c + 32;
				} else if (c >= 48 && c <= 59)
				{
					c = c;	// number, colon, semicolon
				} else if (c >= 65 && c <= 90 && (event.shiftKey == true || event.shiftLeft == true))
				{
					c = c;
				} else 
				{
					c = 32;	// space (nothing)
				}
				cc = String.fromCharCode(c);
				if (obj != null)
				{
					obj.insertAdjacentHTML("beforeEnd", cc);
				}
			}
			return true;
		}
	}	
}

function dontEdit() {
	return false;
}

// Start the update timer
function setTimers()
{
	if (plExit == false)	{
		timeID = window.setTimeout( "updateAll()", refreshRate );
	}
}

// Start to update and reset the update timer
function updateAll()
{
	window.clearTimeout( timeID );
	checkScrollBottom();
	getNewText();	
	setTimers();
}

function getNewText()
{
	rnd++;
	userid = location.search.substring( 1, location.search.length );
	url = 'Server.aspx?action=NewText&u=' + userid + '&session=' + rnd;	
	req = getAjax();

	req.onreadystatechange = function(){
		if( req.readyState == 4 && req.status == 200 ) {					
			var s = req.responseText;
			if (s != null && s != "")
			{
				handleIncomingReq(s);
			}
		}
	}
	
	req.open( 'GET', url, true );
	req.send( null );
}

function postText()
{
	rnd++;
	var chatbox = document.getElementById( "mytext" );
	if (isSendingCommand == true)
	{
		chatbox.enabled = "false";
	}
	chat = chatbox.value;
	chatbox.value = "";	
	// HERE: User entering text
	userid = location.search.substring( 1, location.search.length );
	url = 'Server.aspx?action=PostMsg&u=' + userid + '&t=' + encodeURIComponent(chat) + '&session=' + rnd;

	isSendingCommand = true;
	req = getAjax();
	
	req.onreadystatechange = function(){	
		if( req.readyState == 4 && req.status == 200 ) {
			isSendingCommand = false;
			chatbox.enabled = "true";
		}	
	}
	
	req.open( 'GET', url, true );
	req.send( null );
}

function getElement( id ) 
{
	if( isIE ) {
		return document.all[ id ];
	}
	else {
		return document.getElementById( id );
	}
}

function getElementOfWindow( w, id ) 
{
	if( isIE ) {
		return w.document.all[ id ];
	}
	else {
		return w.document.getElementById( id );
	}
}

function scrollChatPane()
{
	if (dontScroll == false)
	{
		var obj = document.getElementById("chatpane");
		if (obj == null)
		{
			alert("CHATPAN was null?");
			return;
		}
		obj.scrollTop = obj.scrollHeight;
	}
}

function mouseInTextEntry( event )
{
	if (dontScroll == true)
	{
		setFocus( "mytext" );
		resumeScroll();
		scrollChatPane();
	}
	return true;
}

function checkScrollBottom()
{
	var obj = document.getElementById("chatpane");
	if (obj == null) alert("Chatpane was null in checkScrollBottom!");
	if (dontScroll == true)
	{		
		if ((obj.scrollTop + myHeight + 100) > obj.scrollHeight)
		{
			setFocus( "mytext" );
			resumeScroll();
			scrollChatPane();
			//alert(obj.scrollTop + " ... " + obj.scrollHeight + " ... " + myHeight);
		}
	}
	else if (dontScroll == false)
	{
		if ((obj.scrollTop + myHeight + 100) < obj.scrollHeight)
		{
			stopScroll();
			// alert(obj.scrollTop + " ... " + obj.scrollHeight + " ... " + myHeight);
		}
	}
	return true;
}

function kdInChatPane( event )
{
	if(event.ctrlKey == true || event.ctrlLeft == true)
	{
		stopScroll();
		return true;
	}
	else
	{
		setFocus( "mytext" );
		resumeScroll();
		scrollChatPane();
		return true;
	}	
}

function resumeScroll()
{
	dontScroll = false;
}

function stopScroll()
{
	dontScroll = true;
}

function setFocus(ControlName)
{
	var control = document.getElementById(ControlName);
	if( control != null )
	{
		control.focus();
	}
}

function FocusWindow()
{
	window.focus();
}

function retrieveWindowSize()
{
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}  
	
//		var obj = document.getElementById("ad1");
//		if (obj != null) {
//			obj.style.pixelTop = myHeight - 62;
//			obj.style.pixelLeft = 2;
//			obj.style.visible = true;
//		}

}

function doProperSizing()
{
	var chpane = document.getElementById("chatpane");
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}  
	if (chpane != null)
	{
		var o1 = document.getElementById("bottomTable");
		if (o1 != null)
		{	
			o1.style.pixelLeft = 4;
			o1.style.pixelTop = myHeight - 68;
		}
		var o2 = document.getElementById("statusprompt");
		if (o2 != null)
		{
			o2.style.pixelLeft = myWidth - 560;
			o2.style.pixelTop = myHeight - 54;
		}
		chpane.style.height = myHeight - 70;
		setFocus('mytext');
	}	
}

function checkEchoBackStatus() 
{
	var chk = document.getElementById( "echoCheck" );			
	if (chk.value == "on")
	{
		chk.value = "off";
	}
	else
	{
		chk.value = "on";
	}
	return true;
}


function GetCharDesc()
{
	rnd++;
	userid = location.search.substring( 1, location.search.length );
	url = 'Server.aspx?action=CharDesc&u=' + userid + '&session=' + rnd;	
	req = getAjax();

	req.onreadystatechange = function(){
	
		if( req.readyState == 4 && req.status == 200 ) {		
			var s = req.responseText;
			var w = window.open('GeneralInfo.htm','Description','location=0,menubar=0,status=0,toolbar=0,height=150,left=0,top=0,width=200,directories=0',false);
			var txt = getElementOfWindow(w, "infotext");
			alert(txt.toString());
			if (txt != null)
			{
				txt.innerHTML = s;
			}
//			if ( window.frames != null ) {
//				 for ( i = 0; i< window.frames.length; i++ )
//					window.alert ("Child window " +i+ " is named "+window.frames(i).name);
//			}
		}	
	}
	
	req.open( 'GET', url, true );
	req.send( null );
}


function reqRespObjValue( strAct, strCtrl )
{
	rnd++;
	userid = location.search.substring( 1, location.search.length );
	url = 'Server.aspx?action=' + strAct + '&u=' + userid + '&session=' + rnd;	
	req = getAjax();

	req.onreadystatechange = function(){	
		if( req.readyState == 4 && req.status == 200 ) {		
			obj = document.getElementById( strCtrl );
			var s = req.responseText;
			if (obj != null && s != null)
			{				
				obj.value = s;
			}
		}	
	}
	
	req.open( 'GET', url, true );
	req.send( null );
}

function displayLastCommand()
{
	reqRespObjValue("LastCommand", "mytext");
}

function displayNextCommand()
{
	reqRespObjValue("NextCommand", "mytext");
}
