var rooms;
var codeToUsername;
jQuery(document).ready(function(){
	if(document.getElementById('main_chat_div')) //if the chat exists
	{
		if(window.ArrayHash){
			rooms = new ArrayHash();
			codeToUsername = new ArrayHash();
			codeToActorCode = new ArrayHash();
		}
		createPublicRoom();
		createPublicRoom("true"); //the global public
	}
	
});
var currentGroup="public";
var currentGroupGlobal="public";

function showChat(){
	if (jQuery("#main_chat_div").css('display')=="none"){
			var wid = jQuery("#s_slideComp").width();
		jQuery("#main_chat_div").css('position','fixed');
		jQuery("#main_chat_div").css("bottom", "10px");
		jQuery("#main_chat_div").css("right", "0px");
		jQuery("#main_chat_div").css("width", '65%');
		jQuery("#main_chat_div").show();
	  if (document.getElementById('imDiv'))
	  	document.getElementById('imDiv').parentNode.removeChild(document.getElementById('imDiv'));
	  	
	  	 var tmp1 = document.getElementById("public");
			tmp1.scrollTop = tmp1.scrollHeight;
				
				
  focusHandler();
  }else{
		jQuery("#main_chat_div").hide();
	}
	
	
}

function switchChats(){
	if (jQuery("#chatTable_global").css('display')=="none"){
		
		jQuery("#chatTable_global").css('display','');
		jQuery("#chatTable").css('display','none');
		rooms.getItem('public_global').showChatRoom();
		rooms.getItem('public_global').showUsers();
		/*var sel = jQuery("#privateMessages_global").find(".privateMessage");
		
		if (sel!=null && sel.length>0){
			currentGroup = jQuery(sel[0]).attr('id');
		}else{
			rooms.getItem('public').showChatRoom();
		}*/
		
		
		
	}
	else{
		
		jQuery("#chatTable").css('display','');
		jQuery("#chatTable_global").css('display','none');
		rooms.getItem('public').showChatRoom();
		rooms.getItem('public').showUsers();
		
		
		
	}
}

function createPublicRoom(isGlobal){
	var global = "";
	if(isGlobal == "true")
	{
		global="_global";
	}
	
	var roomid = "public"+global;
	var iconId = "public"+global;
	var roomUsers = jQuery("#activeChatUsers"+global+" li"); //get all users, as Java printed them
	var isPrivate = true;
	var sender = document.getElementById("user").value;
	
	var container = document.getElementById("privateMessages"+global);
	var users = new Array();
	
	//Load all the users that are already online (as java printed them)
	for(var i=0;i<roomUsers.length;i++){
		users.push(roomUsers[i].getAttribute("code"));
		codeToUsername.setItem(roomUsers[i].getAttribute("code"), roomUsers[i].innerHTML);
		codeToActorCode.setItem(roomUsers[i].getAttribute("code"), roomUsers[i].getAttribute("actorCode"));
	}
	//users = jQuery.grep(users, function(value) { return value != sender; }); //remove yourself
	
	if (!rooms.getItem(roomid)) {
		//The html should already be created by java
		var tmp_obj = new chatRoom(roomid,users,iconId,isPrivate,isGlobal);
		rooms.setItem(roomid, tmp_obj);
		if(isGlobal != "true")
		{	
			tmp_obj.showChatRoom();
			tmp_obj.showUsers();
		}
	}else{
		rooms.getItem(roomid).showChatRoom();
		rooms.getItem(roomid).showUsers();	//Force it to update the users
	}	
}


function createPrivateRoomInt() {
	
	var sender = document.getElementById("user").value;
	var container = document.getElementById("privateMessages");
	var msgSender;
	var selUsers = jQuery("#chatUser[selected=true]");
	
	if(arguments[0])
		selUsers = jQuery("#chatUser_global[selected=true]");
	if (selUsers.length<=0){
		alert(getMessage(71));
		return;
	}
	var roomId =  Math.ceil( Math.random() * Math.pow(10, 12) ) +'_'+ sender ;
	var iconId = "ICON_"+roomId;
	var users = new Array();
	users.push(sender);
	for(var i=0;i<selUsers.length;i++){
		users.push(selUsers[i].getAttribute("code"));
		roomId+="_"+selUsers[i].getAttribute("code");
		iconId+="_"+selUsers[i].getAttribute("code");
	}
	iconId = iconId.substring(0,iconId.length-1);
	var global="";
	if(arguments[0]){
		global = arguments[0];
		container = document.getElementById("privateMessages_global");
	}
	
	//see if the room exists with a different name, and figure out which ID to use
	roomId = decideID(roomId, users);
	//if private chatroom is not created try to do so 
	if (!rooms.getItem(roomId) ) {		
		container.innerHTML += "<div id='"+roomId+"' class='privateMessage inactiveChatRoom' ><span id='chatHeader'>"+getMessage(41)+"</span><div style='border-bottom: 1px solid #B8CFE5; margin-top: 5px;'></div><br /></div>";
		var tmp_obj = new chatRoom(roomId,users,iconId,true,global);
		rooms.setItem(roomId, tmp_obj);
		room = rooms.getItem(roomId);
		room.showChatRoom();
	}else{
		rooms.getItem(roomId).showChatRoom();
	}
}

//Ext for External (when a new message arrives)
function createPrivateRoomExt(roomId,users,iconId,isPrivate,global){
	//if private chatroom is not created try to do so 
	if (!rooms.getItem(roomId) ) {
		var container;
				
		if (global=="true")
			container = document.getElementById("privateMessages_global");
		else
			container = document.getElementById("privateMessages");
					
		container.innerHTML += "<div id='"+roomId+"' class='privateMessage inactiveChatRoom'  ><span id='chatHeader'>"+getMessage(41)+"</span><div style='border-bottom: 1px solid #B8CFE5; margin-top: 5px;'></div><br /></div>";
		var tmp_obj = new chatRoom(roomId,users,iconId,true,global);
		rooms.setItem(roomId, tmp_obj);
	}
}

// If the room exists, returns the ID of the existing room.
// If not it just returns back the same id
function decideID(roomid, users){
	//if the room exists, the whole thing is pointless
	if (rooms.getItem(roomid)){return roomid;} 
	
	var sameRoom = false;
	//We need to ensure we dont have an identical room. 
	//So we will go through all rooms and look for the same users!
	var keys = rooms.getIndex();
	for( var i=0 ; i < keys.length ; i++ )
	{
		room = rooms.getItem(keys[i]);
		if(users.length != room.users.length){ continue; }//if the rooms have different sizes, they are definately not the same
		if(keys[i] == "public" || keys[i] == "public_global"){ continue; }//And its ok to have all the users of public
		sameRoom = true;
		// go through each user of the room, and see if he is in the room list we are trying to create
		for( var j=0 ; j < room.users.length ; j++ )
		{	
			if( jQuery.inArray(room.users[j], users) < 0 ) //if even one user is not, its enough to break
			{
				sameRoom = false;
				break;
			}						
		}
		if( sameRoom == true )  //Aha! So it is the same group
		{
			return keys[i];
		}		
	}
	return roomid;
}

// flashes (changes) the document title
function flashTitle(newMsg){
	if (newMsg == null) return;

	if (!document.getElementById('imDiv') && jQuery("#main_chat_div").css('display')=="none"){
				var imDiv = document.createElement('div');
				imDiv.setAttribute("id","imDiv");
				//imDiv.setAttribute("style","position:fixed;right:10px;bottom:0px;z-index:100");
				document.body.appendChild(imDiv);
				document.getElementById('imDiv').innerHTML="<img style='cursor:pointer;' onclick='document.getElementById(\"imDiv\").parentNode.removeChild(document.getElementById(\"imDiv\"));showChat();' title='"+getMessage(20)+"' width='25' height='25' border='0' src='/platonimages/images/icon-chat.png'/>";
				
				var title = document.title;
	
				if (title.indexOf(newMsg) < 0) document.title += newMsg;
				else if (title.indexOf(newMsg) > -1) document.title = title.substring(0,title.indexOf(newMsg));
				else { return;}
			}
		
		
	
}

function getTimestamp() {
	var d = new Date();
	return "["+checkTime(d.getHours())+":"+checkTime(d.getMinutes())+"]";
}

function checkTime(i){
	if (i<10) 
		i="0" + i;
	return i;
}

/* // Htan na xrisimopoithei gia na mporeis na grafeis minimata sto history me ajax. Den teleiopoiithike
function foo(){}
function addMessageToHistory( message ) {
	var strParams="action=addMessageToHistory";
	
	var actorCode = document.getElementById('thisActorCode').value;
	
	if (actorCode){
		strParams+="&actorCode="+actorCode;
		strParams+="&receiver="+"all";
		strParams+="&isPrivate="+"false";
	}
	
	new net.ContentLoader("chat",foo,errorState,"POST",strParams);	
}*/

function getChatMessage() {
	var actorCode = document.getElementById('thisActorCode').value;
	var strParams="action=getMessage";
	if (actorCode)
			strParams+="&actorCode="+actorCode;
	if(browserName=="Microsoft Internet Explorer" && (navigator.appVersion.indexOf('MSIE 7.0')>=0 || navigator.appVersion.indexOf('MSIE 6.0')>=0)){
		return;
	}
	
	//if (arguments[0])
	//	strParams+="&global=true";
	jQuery.ajax({  
        type:"POST",
        url: "chat",
        data: strParams,   
        error: function(jqXHR, textStatus){ errorHandler(jqXHR,textStatus,false) } ,
        success: function(data, textStatus, jqXHR){ onGetMessage(jqXHR) } 
    })
	
}

function getChatMessageGlobal() {
	var actorCode = document.getElementById('thisActorCode').value;
	var strParams="action=getMessage";
	if (actorCode)
			strParams+="&actorCode="+actorCode;
	if(browserName=="Microsoft Internet Explorer" && (navigator.appVersion.indexOf('MSIE 7.0')>=0 || navigator.appVersion.indexOf('MSIE 6.0')>=0)){
		return;
	}
	
	//if (arguments[0])
	strParams+="&global=true";
	jQuery.ajax({  
        type:"POST",
        url: "chat",
        data: strParams,  
        error: function(jqXHR, textStatus){ errorHandler(jqXHR,textStatus,true) } ,
        success: function(data, textStatus, jqXHR){ onGetMessageGlobal(jqXHR) } 
    })
}


function errorHandler(jqXHR,textStatus,isGlobal){
    //If the request timed out retry it!
    //if ( textStatus == "timeout" )
   //alert(textStatus);
    if( isGlobal == false)
        setTimeout("getChatMessage()",3000);
    else
        setTimeout("getChatMessageGlobal()",3000);
    return 1;
   
    //Print an error dialog
    // errorState();

}

function sendMessage() {
	
	var actorCode = document.getElementById('thisActorCode').value;
	var global="";
	if (arguments[1]){
		global="_global";
	}
	var st = window.location.href;	
	var user = document.getElementById("user").value;
	if (user == '')
		user = "anonymous";
		
	var isPrivate = "false";
	var receiver="";
	if (currentGroup!="public"+global){
		isPrivate="true";
		var users = rooms.getItem(currentGroup).users;
		for (var i=0;i<users.length;i++)
			{
				receiver+=users[i]+";";
			}
	}else
		receiver="all";
		
	if (document.getElementById('messageChat'+global).value!=""){
		mess = document.getElementById('messageChat'+global).value;
		var strParams = "message="+mess;
			strParams+="&event=chatMessage";
			strParams+="&userkey="+user;
			strParams+="&username="+codeToUsername.getItem(user);
		
		if (actorCode)
			strParams += "&actorCode="+actorCode+"&receiver="+receiver+"&isPrivate="+isPrivate+"&roomId="+currentGroup;
		if (arguments[1])
			strParams+="&global=true";		
			
		jQuery.ajax({  
            type:"POST",
            url: "chat",
            data: strParams,
            error: function(jqXHR,textStatus){ errorState(jqXHR,textStatus) } ,
            success: function(data, textStatus, jqXHR){ onSendMessage() } 
        })
		document.getElementById('messageChat'+global).value="";
	}
}

function onSendMessage() {
	
}

function selectUser(el){
	var sender = document.getElementById("user").value;	//the user who double clicked for private chat
	if (sender == jQuery(el).attr("code")) {			//cannot chat with yourself, you selfish pig!
		alert("You can't chat with yourself!");
		return;
	}
	if (jQuery(el).attr("selected")=="true"){
		jQuery(el).attr("style","");
		jQuery(el).attr("selected","false");
	}else{

		jQuery(el).attr("style","color: red; font-weight: bold; display: block;");
		jQuery(el).attr("selected","true");
	}
}

function chatRoom(roomid,users,iconId,isPrivate,global){
	this.id=roomid;
	this.users=users;
	this.iconId=iconId;
	this.isPrivate=isPrivate;
	this.isGlobal=global;
	this.currentUserCode = document.getElementById('user').value;
	
	
	// blinks an icon modifying its opacity. Param should be "#<id>"
	this.blinkIcon = function() {
		if (this.iconId == null || this.iconId == "") return;
		if (jQuery("#"+this.iconId).css('opacity') == 1) {
			jQuery("#"+this.iconId).css({'opacity': '0.0'}); //hide
			return;
		}
		jQuery("#"+this.iconId).css({'opacity': '1.0'}); //show
	}


	this.addMessage = function(message){
		
		//find sender of msg
		var msgSender = message.substring(24+8,message.indexOf("&nbsp;")-1);	//8 is the length of the timestamp + one space
	
	    var tmp1 = document.getElementById(this.id);
	    tmp1.innerHTML += message+"<br />";
		
					
		if (msgSender == document.getElementById("user").value) return;
		//Blink icon and if private chatroom is hidden
		if (jQuery(tmp1).hasClass("inactiveChatRoom") && interval3 == 0){
			interval3 = window.setInterval("rooms.getItem('"+this.id+"').blinkIcon()", 600);
		}
		tmp1.scrollTop = tmp1.scrollHeight; //scroll to bottom
	}
				
	 this.destroyChatRoom = function(){
		var global="";
		if (this.isGlobal=="true")
			global="_global";
		var tmp = document.getElementById("privateChatImages"+global).childNodes;
		var tmp2 = document.getElementById("privateMessages"+global).childNodes;			
		
		//remove image
		for (var i=0; i<tmp.length; i++) {
			if (tmp[i].getAttribute("id") == "public_chatroom_img") continue;	//if image is public chatroom icon don't count it
			
			if (tmp[i].getAttribute("id") == this.iconId) {
					tmp[i].parentNode.removeChild(tmp[i]);		//removes image
				
			i = tmp.length;	// exit loop after removal.
			}
		}
			
		//remove chatroom
		for (var i=0; i<tmp2.length; i++) {
			if (tmp2[i].getAttribute("id") == this.id) {
				tmp2[i].parentNode.removeChild(tmp2[i]);	//removes chat room
				i = tmp2.length;	// exit loop after removal.
			}
		}
			
		//return to public
		rooms.getItem('public'+global).showChatRoom();
		
	 	rooms.removeItem(this.id);
	}
	
	this.addPrivateChatIcon = function(){
		//if there are no existing private message icon, add an icon
		var global="";	
		if (this.isGlobal=="true")
				global="_global";
				
		if (document.getElementById(iconId) == null ) {
			//find if there are any other images
			var array = document.getElementsByName("linkImagesPrivate"+global);
				
			//append new image
			document.getElementById("privateChatImages"+global).innerHTML += 
				"<img id='"+iconId+"' name='linkImagesPrivate"+global+"' title='private chat between "+iconId+"' height='18' width='22' "+
				"src='/platonimages/images/icon-chat.png' class='linkImagesPrivate' "+
				"onclick=\"rooms.getItem('"+this.id+"').showChatRoom()\" "+
				"ondblclick=\"rooms.getItem('"+this.id+"').destroyChatRoom()\">";
			return true;
		}
		return false;
	}
	
	
	//Brings this chatroom to front
	this.showChatRoom = function() {
		
		currentGroup=this.id;
		
		jQuery(".linkImagesPrivate").attr('src' , '/platonimages/images/icon-chat.png');
		var roomIcon = jQuery("#" + iconId);
		roomIcon.attr('src' , '/platonimages/images/icon-chat-current.png');
		
		var global="";
		if (this.isGlobal=="true")
			global="_global";
		var activeRoom = jQuery(".activeChatRoom");
					
		//if private chatroom already open, abort. else bring it up and hide the rest
		if ( this.id == activeRoom.attr("id") ) { return ;}
		//hide the previous chat
		activeRoom.removeClass("activeChatRoom");
		activeRoom.addClass("inactiveChatRoom");
		//make visible the one we want
		activeRoom = jQuery("#"+this.id);
		activeRoom.addClass("activeChatRoom");
		activeRoom.removeClass("inactiveChatRoom");
		
		//and scroll to bottom (has to be after its made visible)		
		activeRoom.get(0).scrollTop = activeRoom.get(0).scrollHeight;
		
		this.showUsers();
		
		//stop blinking icon, if any
		interval3 = window.clearInterval(interval3);
		interval3 = 0;
		jQuery("#"+iconId).css({'opacity': '1.0'});		
	}
	
	this.showUsers = function(){
		var global="";
		var allUsers = new Array();
		// The idea is to take all and print them accordingly, so define "all"
		if (this.isGlobal=="true")
		{
			global="_global";
			tmpUsers = rooms.getItem('public_global').users;
			// For global, we only need to know the users of bopen, unless we are bopen ourselves! (needs so much fixing!)
			if( document.getElementById("thisActorCode").value != "Bopen" ){
				for(var i=0; i < tmpUsers.length; i++){
					if( codeToActorCode.getItem(tmpUsers[i]) == "Bopen" ){
						allUsers.push(tmpUsers[i]);
					}	
				}
			}
			else
			{	allUsers = tmpUsers;	}
		}
		else
		{	allUsers = rooms.getItem('public').users;	}
				
				
		var containerActive = document.getElementById("activeChatUsers"+global);	
		containerActive.innerHTML = "";
		var containerUsers = document.getElementById("chatUsers"+global);	
		containerUsers.innerHTML = "";
				
		for(var i=0; i < allUsers.length; i++){
		
			var pretty_title = codeToUsername.getItem(allUsers[i]);
			//If we are looking global channels, and we are bopen, let us know where the user is from
			if( document.getElementById("thisActorCode").value == "Bopen" && this.isGlobal=="true" )
				pretty_title += " ("+codeToActorCode.getItem(allUsers[i])+")";
			
			if( this.currentUserCode == allUsers[i] ){ 
				continue;
			}
			else if( jQuery.inArray( allUsers[i], this.users ) >= 0 ){
				containerActive.innerHTML += ("<li id='chatUser"+global+"' name='chatUser' selected='false' code='"+allUsers[i]+"' onclick='selectUser(this)' title='"+codeToUsername.getItem(allUsers[i])+" ("+allUsers[i]+")'>"+pretty_title+"</li>");
			}
			else{
				containerUsers.innerHTML += ("<li id='chatUser"+global+"' name='chatUser' selected='false' code='"+allUsers[i]+"' onclick='selectUser(this)' title='"+codeToUsername.getItem(allUsers[i])+" ("+allUsers[i]+")'>"+pretty_title+"</li>");
			}
				
		}
	}
	
	this.addUserToChat = function(userCode){
		//If the user does not exist in the channel, add him
		if( jQuery.inArray( userCode, this.users ) < 0 )
		{
			this.users.push(userCode);
			if( this.id != "public_global" || codeToActorCode.getItem(userCode) == "Bopen"){	//Only let the global channel know if Bopen users log 
				// let the channel know
				var message = getTimestamp()+"&nbsp<span class=\"alert\" >"+codeToUsername.getItem(userCode)+" joined the chat.</span>";
				this.addMessage(message);	
			}			
			var activeRoomID = jQuery(".activeChatRoom").attr("id");
			rooms.getItem(activeRoomID).showUsers();
			
		}
	}
	
	this.removeUserFromChat = function(userCode){
		var tmpLength = this.users.length;
		this.users = jQuery.grep(this.users, function(value) { return value != userCode; });
		// assuming he was in the chat, let the channel know
		if( tmpLength > this.users.length)
		{
			if( this.id != "public_global" || codeToActorCode.getItem(userCode) == "Bopen"){	//Only let the global channel know if Bopen users log off
				var message = getTimestamp()+"&nbsp<span class=\"alert\" >"+codeToUsername.getItem(userCode)+" has left the chat.</span>";
				this.addMessage(message);
			}
			
			// refresh the users of the active chat
			var activeRoomID = jQuery(".activeChatRoom").attr("id");
			rooms.getItem(activeRoomID).showUsers();
			
		}
	}
	
	this.addPrivateChatIcon();
	
}

function onGetMessage(jqXHR){
	
	var doc=jqXHR.responseXML;

	var isGlobalXML = doc.getElementsByTagName("global");
	var status 	 = doc.getElementsByTagName("status");
	var event 	 = doc.getElementsByTagName("event");
	var userkey	 = doc.getElementsByTagName("userkey");
	var username = doc.getElementsByTagName("username");
	var actorCode= doc.getElementsByTagName("actorCode");
	var message  = doc.getElementsByTagName("message");
	var users 	 = doc.getElementsByTagName("users");	//eg. George Fylaktopoulos
	var code 	 = doc.getElementsByTagName("code");	// the corresponding code of the user (for example bkara)
	var receiver = doc.getElementsByTagName("receiver"); //receiver's code
	var roomId 	 = doc.getElementsByTagName("roomId"); //receiver's code
	var st 		 = document.getElementById("chatContent");
	var currentUser = document.getElementById("user").value; //hidden input, in any page, which stores the current user
	var userIsSender = false;
	var rcv		= null; //stores the receiver
	var sender	= null; //stores the sender
	var msgIsPrivate = false;
	var chatroomWidth;
	var mess = message[0].firstChild;	//stores the message contained in the response
	if(mess){
		mess = message[0].firstChild.nodeValue;
	}else{
		getChatMessage();
		return;
	}
	var timestamp; //stores the timestamp included in the message.
	var isGlobal = "false";
	var global = "";
	if (isGlobalXML[0]!=null && isGlobalXML[0].firstChild)
		isGlobal=isGlobalXML[0].firstChild.nodeValue;
	if (isGlobal=="true")
		global = "_global";
		
	//if there is an error, abort.
	if (status == null || status[0]==null || status[0].firstChild==null) {
		getChatMessage();
		return;
	}
	else if (status[0].firstChild.nodeValue == -1){ //|| status[0].firstChild.nodeValue == -2) {	// -1 = user is not logged in
		return;
	}
	else if ( status[0].firstChild.nodeValue == -2 || status[0].firstChild.nodeValue == -5 || status[0].firstChild.nodeValue == -6) {	// -1 = user is not logged in
		getChatMessage();
		return;
	}
	else if (status[0].firstChild.nodeValue == -3) {	// -3 = private message of other
		if (st != null) {
			getChatMessage();
		}
		return;
	}
	
	event 	 = event[0].firstChild.nodeValue;
	userkey	 = userkey[0].firstChild.nodeValue;
	actorCode= actorCode[0].firstChild.nodeValue;
	
	//And what room is that?
	if (roomId!=null && roomId[0]!=null && roomId[0].firstChild!=null)
		roomId=roomId[0].firstChild.nodeValue;
	else
		roomId="public";
	var users = new Array();
	
	//get all the users included in the message
	rcv = receiver[0].firstChild.nodeValue;
	if(rcv != "all") 
	{		
		users = rcv.split(";");	// <-that will add an empty user at the end of table
		users.pop();	//remove him
	}
	
	// If the room does not exist see if its desquised under a different name
	if (!rooms.getItem(roomId)){
		roomId = decideID(roomId, users);
	}	
	var room = rooms.getItem(roomId);
	
	//See what is the event of this message!
	//==================== EVENT : chatMessage ======================
	if( event == "chatMessage" )
	{	
		//remove timestamp. (temporarily)
		timestamp = mess.substring(0, mess.indexOf("]")+1);
		mess = mess.substring(mess.indexOf("]")+2);
	
		// Lets format the message a bit
		var pretty_title = codeToUsername.getItem(userkey);
		//If we are looking global channels, and we are bopen, let us know where the user is from
		if(  isGlobal=="true" )
			pretty_title += " ("+codeToActorCode.getItem(userkey)+")";
				
		mess = timestamp+"&nbsp<span class='usersname'>"+pretty_title+":&nbsp;&nbsp;&nbsp;</span>"+mess;		
	
		
		if (roomId != 'public' && roomId != 'public_global') 
		{					
			if (rooms.getItem(roomId)){
				rooms.getItem(roomId).addMessage(mess);
			}
			else // Create the room, then add the message
			{			
				createPrivateRoomExt(roomId,users,"ICON_"+roomId,true,isGlobal);
				room = rooms.getItem(roomId);
				room.addMessage(mess);
			}
				
			if ( ((interval2 == null || interval2 == undefined || interval2 == 0) && st!=null && !st.currentStyle) || (jQuery("#main_chat_div").css('display')=="none") ) 
			{	
				flashTitle(' - New chat message!');
			}			
		}
		else
		{
			room = rooms.getItem('public'+global);
			room.addMessage(mess);
		}
			
		
	}
	//==================== EVENT : Joined Chat ======================
	else if( event == "joinedChat" )
	{	
		// If he joined public && its our public ,add him to our public
		if(room.id == "public" && actorCode.toLowerCase() == document.getElementById("thisActorCode").value.toLowerCase())
		{	
			codeToUsername.setItem(userkey, username[0].firstChild.nodeValue);
			codeToActorCode.setItem(userkey, actorCode);			
			room.addUserToChat(userkey,actorCode);
		}
		// and in any case, add him to global public		
		codeToUsername.setItem(userkey, username[0].firstChild.nodeValue);
		codeToActorCode.setItem(userkey, actorCode);
		rooms.getItem('public_global').addUserToChat(userkey);
				
	}
	//==================== EVENT : Left Chat ======================
	else if( event == "leftChat" )
	{		
		// if he left the chat, remove him from all our rooms no questions asked
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);
			room.removeUserFromChat(userkey);
		}				
		codeToUsername.removeItem(userkey);
		codeToActorCode.removeItem(userkey);
	}
	//==================== EVENT : Joined Chat From a Different Location ======================
	else if( event == "joinedFromDifferentLocation" )
	{		
		// Just let the rooms concered know @@ FIX THAT
		/*
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);	
			
		}		*/
		
		var message = getTimestamp()+"&nbsp<span class=\"systemMsg\" >"+codeToUsername.getItem(userkey)+" has just joined from a different location.</span>";
		rooms.getItem(room.id).addMessage(message);
	}
	//==================== EVENT : left Chat From a Different Location ======================
	else if( event == "leftFromDifferentLocation" )
	{		
		// Just let the rooms concered know @@ FIX THAT
		/*
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);	
			
		}		*/
		var message = getTimestamp()+"&nbsp<span class=\"systemMsg\" >"+codeToUsername.getItem(userkey)+" has logged out from one location.</span>";
		rooms.getItem(room.id).addMessage(message);		
	}
	
	
	
	
	
	//play a sound
	/*if (winHasFocus == false && st!=null && sender != "system") {
		//clear previous audio tags
		var b = document.getElementById("beep");
		if (b != null)
			b.parentNode.removeChild(b);
			
		//create a new audio tag
		
		// FF
		if (document.addEventListener) {
			//	this code uses HTML 5
			var beep = document.createElement("audio");
			beep.setAttribute("src",'/platonimages/servers/Bopen/media/pop.wav'); //http://www.members.tripod.com/~buggerluggs/wavs/pop.wav
			beep.setAttribute("autoplay",'autoplay');
			beep.setAttribute("id",'beep');
			//alert(beep);
			document.body.appendChild(beep);
		}
		// IE
		else {
			var beep = document.createElement("bgsound");
			beep.setAttribute("src", '/platonimages/servers/Bopen/media/pop.wav'); //http://www.members.tripod.com/~buggerluggs/wavs/pop.wav
			beep.setAttribute("autostart",'true');
			beep.setAttribute("loop", '1');
			beep.setAttribute("id",'beep');
			//alert(beep);
			document.body.appendChild(beep);
		}
		//example: <bgsound src="elshad.mid" autostart=true loop=infinite>
		
		//flash title if not IE
		if ((interval2 == null || interval2 == undefined || interval2 == 0) && st!=null && !st.currentStyle) {
			interval2 = window.setInterval("flashTitle(' - New chat message!')", 600);
		}
	}*/
	
	// New message notification. Flash public icon. Get next message.
	if (st != null) {
		/*if (winHasFocus == false && objDiv.style.display == "none" && !msgIsPrivate && sender != "system") {		
			
			//flash the public icon
			if (interval == null || interval == undefined || interval == 0)
				interval = window.setInterval("blinkIcon('#public_chatroom_img')", 600, "JavaScript");
		}*/
		//if (isGlobal=="true")
			getChatMessage();
		//else
		//	getChatMessage();
	}
}
	
	
	
	function onGetMessageGlobal(jqXHR){
	
    var doc=jqXHR.responseXML;

	var isGlobalXML = doc.getElementsByTagName("global");
	var status 	 = doc.getElementsByTagName("status");
	var event 	 = doc.getElementsByTagName("event");
	var userkey	 = doc.getElementsByTagName("userkey");
	var username = doc.getElementsByTagName("username");
	var actorCode= doc.getElementsByTagName("actorCode");
	var message  = doc.getElementsByTagName("message");
	var users 	 = doc.getElementsByTagName("users");	//eg. George Fylaktopoulos
	var code 	 = doc.getElementsByTagName("code");	// the corresponding code of the user (for example bkara)
	var receiver = doc.getElementsByTagName("receiver"); //receiver's code
	var roomId 	 = doc.getElementsByTagName("roomId"); //receiver's code
	var st 		 = document.getElementById("chatContent");
	var currentUser = document.getElementById("user").value; //hidden input, in any page, which stores the current user
	var userIsSender = false;
	var rcv		= null; //stores the receiver
	var sender	= null; //stores the sender
	var msgIsPrivate = false;
	var chatroomWidth;
	var mess = message[0].firstChild;	//stores the message contained in the response
	if(mess){
		mess = message[0].firstChild.nodeValue;
	}else{
		getChatMessageGlobal();
		return;
	}
	var timestamp; //stores the timestamp included in the message.
	var isGlobal = "false";
	var global = "";
	if (isGlobalXML[0]!=null && isGlobalXML[0].firstChild)
		isGlobal=isGlobalXML[0].firstChild.nodeValue;
	if (isGlobal=="true")
		global = "_global";
		
	//if there is an error, abort.
	if (status == null || status[0]==null || status[0].firstChild==null) {
		getChatMessageGlobal();
		return;
	}
	else if (status[0].firstChild.nodeValue == -1) {	// -1 = user is not logged in
		return;
	}
	else if (status[0].firstChild.nodeValue == -2 || status[0].firstChild.nodeValue == -5){// -1 = user is not logged in
		getChatMessageGlobal();
		return;
	}
	else if (status[0].firstChild.nodeValue == -3) {	// -3 = private message of other
		if (st != null) {
			getChatMessageGlobal();
		}
		return;
	}
	
	event 	 = event[0].firstChild.nodeValue;
	userkey	 = userkey[0].firstChild.nodeValue;
	actorCode= actorCode[0].firstChild.nodeValue;
	
	//And what room is that?
	if (roomId!=null && roomId[0]!=null && roomId[0].firstChild!=null)
		roomId=roomId[0].firstChild.nodeValue;
	else
		roomId="public_global"
	var users = new Array();
	
	//get all the users included in the message
	rcv = receiver[0].firstChild.nodeValue;
	if(rcv != "all") 
	{		
		users = rcv.split(";");	// <-that will add an empty user at the end of table
		users.pop();	//remove him
	}
	
	// If the room does not exist see if its desquised under a different name
	if (!rooms.getItem(roomId)){
		roomId = decideID(roomId, users);
	}	
	var room = rooms.getItem(roomId);
	
	//See what is the event of this message!
	//==================== EVENT : chatMessage ======================
	if( event == "chatMessage" )
	{	
		//remove timestamp. (temporarily)
		timestamp = mess.substring(0, mess.indexOf("]")+1);
		mess = mess.substring(mess.indexOf("]")+2);
	
		// Lets format the message a bit
		var pretty_title = codeToUsername.getItem(userkey);
		//If we are looking global channels, and we are bopen, let us know where the user is from
		if(  isGlobal=="true" )
			pretty_title += " ("+codeToActorCode.getItem(userkey)+")";
				
		mess = timestamp+"&nbsp<span class='usersname'>"+pretty_title+":&nbsp;&nbsp;&nbsp;</span>"+mess;		
	
		
		if (roomId != 'public' && roomId != 'public_global') 
		{					
			if (rooms.getItem(roomId)){
				rooms.getItem(roomId).addMessage(mess);
			}
			else // Create the room, then add the message
			{			
				createPrivateRoomExt(roomId,users,"ICON_"+roomId,true,isGlobal);
				room = rooms.getItem(roomId);
				room.addMessage(mess);
			}
				
			if ( ((interval2 == null || interval2 == undefined || interval2 == 0) && st!=null && !st.currentStyle) || (jQuery("#main_chat_div").css('display')=="none") ) 
			{	
				flashTitle(' - New chat message!');
			}			
		}
		else
		{
			room = rooms.getItem('public'+global);
			room.addMessage(mess);
		}
			
		
	}
	//==================== EVENT : Joined Chat ======================
	else if( event == "joinedChat" )
	{	
		// If he joined public && its our public ,add him to our public
		if(room.id == "public" && actorCode.toLowerCase() == document.getElementById("thisActorCode").value.toLowerCase())
		{	
			codeToUsername.setItem(userkey, username[0].firstChild.nodeValue);
			codeToActorCode.setItem(userkey, actorCode);			
			room.addUserToChat(userkey,actorCode);
		}
		// and in any case, add him to global public		
		codeToUsername.setItem(userkey, username[0].firstChild.nodeValue);
		codeToActorCode.setItem(userkey, actorCode);
		rooms.getItem('public_global').addUserToChat(userkey);
				
	}
	//==================== EVENT : Left Chat ======================
	else if( event == "leftChat" )
	{		
		// if he left the chat, remove him from all our rooms no questions asked
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);
			room.removeUserFromChat(userkey);
		}				
		codeToUsername.removeItem(userkey);
		codeToActorCode.removeItem(userkey);
	}
	//==================== EVENT : Joined Chat From a Different Location ======================
	else if( event == "joinedFromDifferentLocation" )
	{		
		// Just let the rooms concered know @@ FIX THAT
		/*
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);	
			
		}		*/
		
		var message = getTimestamp()+"&nbsp<span class=\"systemMsg\" >"+codeToUsername.getItem(userkey)+" has just joined from a different location.</span>";
		rooms.getItem(room.id).addMessage(message);
	}
	//==================== EVENT : left Chat From a Different Location ======================
	else if( event == "leftFromDifferentLocation" )
	{		
		// Just let the rooms concered know @@ FIX THAT
		/*
		var keys = rooms.getIndex();
		for( var i=0; i<keys.length ; i++ ){
			room = rooms.getItem(keys[i]);	
			
		}		*/
		var message = getTimestamp()+"&nbsp<span class=\"systemMsg\" >"+codeToUsername.getItem(userkey)+" has logged out from one location.</span>";
		rooms.getItem(room.id).addMessage(message);		
	}
	
	
	
	
	
	//play a sound
	/*if (winHasFocus == false && st!=null && sender != "system") {
		//clear previous audio tags
		var b = document.getElementById("beep");
		if (b != null)
			b.parentNode.removeChild(b);
			
		//create a new audio tag
		
		// FF
		if (document.addEventListener) {
			//	this code uses HTML 5
			var beep = document.createElement("audio");
			beep.setAttribute("src",'/platonimages/servers/Bopen/media/pop.wav'); //http://www.members.tripod.com/~buggerluggs/wavs/pop.wav
			beep.setAttribute("autoplay",'autoplay');
			beep.setAttribute("id",'beep');
			//alert(beep);
			document.body.appendChild(beep);
		}
		// IE
		else {
			var beep = document.createElement("bgsound");
			beep.setAttribute("src", '/platonimages/servers/Bopen/media/pop.wav'); //http://www.members.tripod.com/~buggerluggs/wavs/pop.wav
			beep.setAttribute("autostart",'true');
			beep.setAttribute("loop", '1');
			beep.setAttribute("id",'beep');
			//alert(beep);
			document.body.appendChild(beep);
		}
		//example: <bgsound src="elshad.mid" autostart=true loop=infinite>
		
		//flash title if not IE
		if ((interval2 == null || interval2 == undefined || interval2 == 0) && st!=null && !st.currentStyle) {
			interval2 = window.setInterval("flashTitle(' - New chat message!')", 600);
		}
	}*/
	
	// New message notification. Flash public icon. Get next message.
	if (st != null) {
		/*if (winHasFocus == false && objDiv.style.display == "none" && !msgIsPrivate && sender != "system") {		
			
			//flash the public icon
			if (interval == null || interval == undefined || interval == 0)
				interval = window.setInterval("blinkIcon('#public_chatroom_img')", 600, "JavaScript");
		}*/
		getChatMessageGlobal();
		
	}
}
	


