// XHTML live Chat
// author: alexander kohlhofer
// version: 1.0
// http://www.plasticshore.com
// http://www.plasticshore.com/projects/chat/
// please let the author know if you put any of this to use
// XHTML live Chat (including this script) is published under a creative commons license
// license: http://creativecommons.org/licenses/by-nc-sa/2.0/

//************************************************************************
// OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS OBS
//*************************************************************************
//var fullpath = "http://localhost/madital"; 
var fullpath = "http://www.madital.dk";
var GetChaturl = "getChatData.php";
var SendChaturl = "sendChatData.php";
var SendOnlineUserurl = fullpath+"/sendOnlineUser.php";
var SendJsSearchurl = fullpath+"/sendJsSearch.php";
var GetOnlineUserurl = fullpath+"/ajaxchat/getOnlineUsers.php";
var lastID = -1; //initial value will be replaced by the latest known id
//window.onload = initJavaScript;

function initJavaScript() {
	//alert("initJavaScript - det testes i øjeblikket. Mvh Lone");
	//getOnlineUsers();
	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(); //initiates the first data query
	//sendOnlineUser('7', 'y');
}

//initiates the first data query
function receiveChatText() {
	//alert("receiveChatText");
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
	//alert(GetChaturl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000));
  	httpReceiveChat.open("GET",GetChaturl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveChat.onreadystatechange = handlehHttpReceiveChat; 
  	httpReceiveChat.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
	//alert("handlehHttpReceiveChat");
  if (httpReceiveChat.readyState == 4) {
  	res = httpReceiveChat.responseText.split('---||---')
	var online_brugere = res[0];
	//alert(online_brugere);
	if (document.getElementById("onlineoutput")){
		document.getElementById("onlineoutput").innerHTML = online_brugere;
    
		//results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
		results = res[1].split('---');
	    if (results.length > 2) {
		    for(i=0;i < (results.length-1);i=i+3) { //goes through the result one message at a time
		    	insertNewContent(results[i+1],results[i+2]); //inserts the new content into the page
		    }
		    lastID = results[results.length-4];
	    }
    }
	setTimeout('receiveChatText();',2000); //executes the next data query in x seconds
  }
}

//inserts the new content into the page
function insertNewContent(liName,liText) {
	//alert("insertNewContent");
	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+': ');
	oText = document.createTextNode(liText);
	oSpan.appendChild(oName);
	oLi.appendChild(oSpan);
	oLi.appendChild(oText);
	insertO.insertBefore(oLi, insertO.firstChild);
}

//stores a new comment on the server
function sendComment() {

	//alert("sendComment");
	//ready to send new comment
	currentChatText = document.forms['chatForm'].elements['chatbarText'].value;
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
		currentName = document.forms['chatForm'].elements['name'].value;
		param = 'n='+ currentName+'&c='+ 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 = '';
	document.forms['chatForm'].elements['chatbarText'].focus();
	} else {
		setTimeout('sendComment();',1000);
	}
}

//deals with the servers' reply to sending a comment
function handlehHttpSendChat() {
	//alert("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) {
	//alert("checkStatus");
	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() {
	//alert("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() {
	//alert("getHTTPObject");
  
  //oprindelig kode:
  //var xmlhttp;
  /*@cc_on //ikke udkommenteret af Lone
  @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 xmlHttp=null;
  try
	{
	  // Her oprettes objektet, hvis browseren er: Firefox, Opera 8.0+, Safari (IE7)
	xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
	// Browseren er åbenbart Internet Explorer
	try
	  { // Her oprettes objektet, hvis 'Msxml2.XMLHTTP' understøttes
	  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	  }
	catch (e)
	  { // Her oprettes objektet med 'Microsoft.XMLHTTP', hvis 'Msxml2.XMLHTTP' ikke understøttes
	  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	}
  return xmlHttp;*/
  
}


// initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();

var httpSendJsSearch = getHTTPObject();

//updates online user
function sendOnlineUser(brugerid, chat) {
	//alert("sendOnlineUser");

	if (httpSendChat.readyState == 4 || httpSendChat.readyState == 0) {
		param = 'b_id='+brugerid+'&chat='+chat;
		httpSendChat.open("POST", SendOnlineUserurl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  		//httpSendChat.onreadystatechange = handlehHttpSendChat;
  		httpSendChat.send(param);
		//alert(param);
		if (chat == "y"){
			//brugeren er i chatten
			setTimeout('sendOnlineUser('+brugerid+', "y");',5 * 1000); //5 sek
		}
		else{
			//brugeren er ikke i chatten
			setTimeout('sendOnlineUser('+brugerid+', "n");',3 * 60 * 1000); //3 min
		}
	} else {
		setTimeout('sendOnlineUser('+brugerid+', '+chat+');',1000);
	}
}


//updates online user
function sendJsSearch(str) {
	//alert("sendOnlineUser");

	if (httpSendJsSearch.readyState == 4 || httpSendJsSearch.readyState == 0) {
		param = 'str='+str;
		httpSendJsSearch.open("POST", SendJsSearchurl, true);
		//alert("Websitet testes pt");
		httpSendJsSearch.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  		//httpSendJsSearch.onreadystatechange = handlehHttpSendChat;
  		httpSendJsSearch.send(param);
	} else {
		setTimeout('sendJsSearch('+str+');',1000);
	}
}


/*
var httpReceiveOnlineChatUsers = getHTTPObject();

function getOnlineUsers(){
	//alert("receiveChatText");
	if (httpReceiveOnlineChatUsers.readyState == 4 || httpReceiveOnlineChatUsers.readyState == 0) {
	//alert(GetChaturl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000));
  	httpReceiveOnlineChatUsers.open("GET",GetOnlineUserurl + '?lastID=' + lastID + '&rand='+Math.floor(Math.random() * 1000000), true);
    httpReceiveOnlineChatUsers.onreadystatechange = handlehHttpReceiveChat2; 
  	httpReceiveOnlineChatUsers.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat2() {
	//alert("handlehHttpReceiveChat");
  str = "";
  if (httpReceiveOnlineChatUsers.readyState == 4) {
  	//alert(httpReceiveOnlineChatUsers.responseText);
    //results = httpReceiveOnlineChatUsers.responseText.split('---'); //the fields are seperated by ---
    //if (results.length >= 0) {
	//    for(i=0;i <= (results.length-1);i=i+1) { //goes through the result one message at a time
	//    	str += results[i]; //inserts the new content into the page
	//    }
    //}
	document.getElementById("onlineoutput").innerHTML = httpReceiveOnlineChatUsers.responseText;
	//alert(str);
    setTimeout('getOnlineUsers();',2000); //executes the next data query in x seconds
  }
}
*/