
var GetChaturl = "/sc/index.php/chats/get";
var SendChaturl = "/sc/index.php/chats/send";
var lastID = -1; //initial value will be replaced by the latest known id
var y=0;
var guest_id;
//window.onload = initJavaScript;

function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};


function initJavaScript() {
	if(document.forms['chatForm']!=null)
	{
	document.forms['chatForm'].elements['chatbarText'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
	checkStatus(''); //sets the initial value and state of the input comment
	checkName(); //checks the initial value of the input name
	receiveChatText(lastID); //initiates the first data query
	guest_id=checkName();
	}
}

//initiates the first data query
function receiveChatText() {
 	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
  	httpReceiveChat.open("GET",GetChaturl + '/' + lastID + '/'+Math.floor(Math.random() * 1000000), true);
    httpReceiveChat.onreadystatechange = handlehHttpReceiveChat; 
  	httpReceiveChat.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
  if (httpReceiveChat.readyState == 4) {
    results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
    if (results.length > 2) {
	    for(i=0;i < (results.length-6);i=i+5) { //goes through the result one message at a time
	    	insertNewContent(results[i+1],results[i+2],results[i+3],results[i+4]); //inserts the new content into the page
	    }
	    y = results[results.length-4];
	    lastID=parseInt(y);
	//insertNewContent("last ID 1",lastID); //inserts the new content into the page
	//insertNewContent("last ID 2",y); //inserts the new content into the page
	//insertNewContent("length",results.length); //inserts the new content into the page
    }
    setTimeout('receiveChatText();',4000); //executes the next data query in 4 seconds
  }
}


//inserts the new content into the page
function insertNewContent(liTime,liName,liText,liSciencePoints) {
	insertO = document.getElementById("outputList");
	oLi = document.createElement('li');
	oSpan = document.createElement('span');
	oSpan.setAttribute('className','name'); //for IE's sake
	oSpan.setAttribute('class','name');
  	oName = document.createTextNode(liName);
	oTime = document.createTextNode(': ' + liTime+'min ago: ');
	oText = document.createTextNode(liText);

	oSpan.appendChild(oTime);
	oLi.appendChild(oSpan);

	var  fontElement = document.createElement("font");
	
	strLength = liText.length;
	var cond1=liName.substr(0,5)!='guest';
	var cond2=strLength>1;
	if(cond1 && cond2)
	{
		// create a new link and a text
   		pickLink=document.createElement('a');
   		pickText=document.createTextNode(liName);

		if(liSciencePoints > 3000)
		{
  			fontElement.setAttribute("color", "#880000");
  			fontElement.setAttribute("size", "5");
  		}
		else
		{
  			fontElement.setAttribute("color", "#888800");
  			fontElement.setAttribute("size", "4");			
		}  	
  		fontElement.appendChild(pickText);

		// add the text as a child of the link
   		pickLink.appendChild(fontElement);

		// set the href to # and call picker when clicked or tabbed to  
   		pickLink.setAttribute('href','/sc/index.php/users/view/'+URLEncode(liName));
   		pickLink.onclick=function(){picker(this);return false;};

		oLi.appendChild(pickLink);
	}
	else
	{
  		fontElement.setAttribute("color", "#008800");
  		fontElement.appendChild(oName);
		oLi.appendChild(fontElement);
	}
	oLi.appendChild(oSpan);
	oLi.appendChild(oText);
	insertO.insertBefore(oLi, insertO.firstChild);
	
}

//stores a new comment on the server
function sendComment() {
	currentChatText = document.forms['chatForm'].elements['chatbarText'].value;
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
		currentName = document.forms['chatForm'].elements['name'].value;
		param = 'data[Chat][name]='+ currentName+'&data[Chat][text]='+ currentChatText;	
		httpSendChat.open("POST", SendChaturl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  	httpSendChat.onreadystatechange = handlehHttpSendChat;
  	httpSendChat.send(param);
  	document.forms['chatForm'].elements['chatbarText'].value = '';
	} else {
		setTimeout('sendComment();',1000);
	}
}

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


//does celver things to the input and submit
function checkStatus(focusState) {
	currentChatText = document.forms['chatForm'].elements['chatbarText'];
	oSubmit = document.forms['chatForm'].elements['submit'];
	if (currentChatText.value != '' || focusState == 'active') {
		oSubmit.disabled = false;
	} else {
		oSubmit.disabled = true;
	}
}

//autoasigns a random name to a new user
function checkName() {
	currentName = document.forms['chatForm'].elements['name'];
	if (currentName.value == '') {
		currentName.value = 'guest_'+ Math.floor(Math.random() * 10000);
	}
}


//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
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;
}


// initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();


