var chatpngsFixed=false;
var TABS = new Array(); /* array of ChatWindow objects, will resemble in chatboxes and upper tabs */
var stopQueries=0; /* if set to 1 the functions will not make ajax request any more */
var stopListRequest=1; /* if set to 1 the functions will not make ajax request any more */
var stopNewMsgNoRefresh=0; /* if set to 1 the functions will not make ajax request any more */
var showedTabs=0;
var RequestID=0; /* the current request id, this is the current user to whom you chat id, if set to 0 function will stop requesting*/
var Old_RequestID=null; /*will be used for the onBlur/onFocus function, the RequestID will be set to 0 after beeing stored here*/
//var speed = Math.round(millisec / 100);
var speed = Math.round(5000); /* Time interval for the new messages requests both groups and user specific messages*/
var requesting_chat_messages = false; /*flag stating if a ajax request is in process for new chat messages*/

var blurred = false; /* flag to state the status of window */

var currentChatBox='chat_box_0'; /*current chat box, keep is in mind so we can hide it,  obsolete*/
var requesting_list_chat_messages = false;
var currentTAB; /*contains the current tab object*/

function isInTabs(userid){
	if(TABS){
	for(i=0;i<TABS.length;i++){
		if(TABS[i].uid==userid)
			return TABS[i];
	}
	}

	return false;

}

function addUserChatTab(userid,username){
	var auxTab=isInTabs(userid);
	if(auxTab==false) {
		TABS[TABS.length]=new ChatWindow(userid,username);
		auxTab=TABS[TABS.length-1];
	}
	auxTab.showChatBox();
	//alert("REQ: "+RequestID);
}


function debugOUT(string){
	//$('debug').innerHTML = $('debug').innerHTML+"<br>"+string;
}

function updateScroll(){
	/* moves the diolog window to the bottom*/
	$('parent_chat_box').scrollTop=document.getElementById('parent_chat_box').scrollHeight;
}

var refreshing_newmsgs=false;

function refreshNewMsgsNo(){
	/* refreshes the field with the new messages number on the page */

	if(stopNewMsgNoRefresh==0){

	setTimeout("refreshNewMsgsNo();",(3*speed));
	//alert("Timed");
	}

	if (refreshing_newmsgs) {
		return false;
	}

				var addr=BASE_URL+'/ajax/messaging/getnewmessagesno.php';

				var myAjax = new Ajax.Request(addr,
									{
										method:'get',
										onFailure: systemError,
										onComplete: newMessagesCountResponse
									});

				refreshing_newmsgs = true;
}

function newMessagesCountResponse(request){
	/* will update the number of new messages fields, and will display the link if the new message count is bigger then 0*/
	var newMsgNo = request.responseText;
	$('newmsgs_no').innerHTML=newMsgNo;
	if(newMsgNo!='0')
		Show('new_messages_status');

	refreshing_newmsgs = false;
}

function getChatUserMessages() {
	/* retrieves new user specific messages*/

	if(stopQueries!=1)
	setTimeout("getChatUserMessages();",(speed));



	/* gets new messages from a certain user to the page's page content area*/
	if (requesting_chat_messages || RequestID==0) {
		return false;
		//if(stopQueries!=1)
			//setTimeout("getChatUserMessages('"+uid+"');",(speed));
	}
	var addr=BASE_URL+'/ajax/messaging/getnewusermessagesxml.php';
	var params='uid='+RequestID;

	var myAjax = new Ajax.Request(addr,
									{
										method:'get',
										parameters:params,
										onComplete: processMessages,
										onFailure: systemError
									});


	requesting_chat_messages = true;


}


function processMessages(request_msg) {

		try{
			if (request_msg.readyState == 4) {
					requesting_chat_messages = false;
				if(request_msg.status == 200) {
					var htmlDoc = request_msg.responseText;

					//document.getElementById('text_div').innerHTML =  "<pre>"+htmlDoc+"</pre>";
					//document.getElementById('status').innerHTML = '';
					requesting_chat_messages = false;
					//delete request_msg;
					//alert(htmlDoc);
					//htmlDoc='{"bindings": [{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}]}';
					var the_object = eval('(' + htmlDoc + ')');
					//alert(the_object);
					//alert(the_object.messages.message[0].id+" "+the_object.messages.message[0].content);
					//return;
						var new_msgs = new Array();
						if(the_object && the_object.messages){
							var messages = the_object.messages;

							for (var i=0;i<messages.length-1;i++) {
							//alert("in for "+ decode(messages[i].content));
								var nextitem = new_msgs.length;
								new_msgs[nextitem] = new Array();
								new_msgs[nextitem]["id"] = messages[i].id;
								new_msgs[nextitem]["uid"] = messages[i].uid;
								new_msgs[nextitem]["username"] = decode(messages[i].username);
								new_msgs[nextitem]["online_state"] = decode(messages[i].online_state);
								new_msgs[nextitem]["date"] = messages[i].date;
								new_msgs[nextitem]["content"] = decode(messages[i].content);

							}
						}

						finalAppend="";

						for(i=0;i<new_msgs.length;i++){
						//debugOUT("Compare "+currentTAB.uid+" with " +new_msgs[i]["uid"])
							if(currentTAB.uid==new_msgs[i]["uid"]) {
								outputTAB=currentTAB;
							}
							else {
								outputTAB=isInTabs(new_msgs[i]["uid"]);
								debugOUT("Different div occurence");
								if(outputTAB==false){
									alert("Something went wrong.");
									return;
								}
							}

							if(new_msgs[i]["date"]=="SYSTEMCOMMAND") {

								if((new_msgs[i]["online_state"]==1 && outputTAB.is_online==0) || (new_msgs[i]["online_state"]==0 && outputTAB.is_online==1) || outputTAB.is_online==null) {
									if(new_msgs[i]["online_state"]==1)
										outputTAB.append("<div style='margin:1px;color:gray;'>"+new_msgs[i]["content"]+"</div>");
									else finalAppend="<div style='margin:1px;color:gray;'>"+new_msgs[i]["content"]+"</div>";

									outputTAB.is_online=new_msgs[i]["online_state"];
									if(currentTAB==outputTAB) {
										updateScroll();
									}
									else {
									outputTAB.highlight();
									}

								}

							}
							else {
								outputTAB.append("<div style='margin:1px;'>["+new_msgs[i]["date"]+"] "+new_msgs[i]["username"]+": "+new_msgs[i]["content"]+"</div>");
							}

						}
						if(finalAppend!="")
							outputTAB.append(finalAppend);

						if(new_msgs.length>1) {
							if(currentTAB==outputTAB)
								updateScroll();
							else outputTAB.highlight();
						}


				}
				else {
					debugOUT('Request error.');
				}
			}

		}
		catch(e){
			// caught an error
			debugOUT('Response failed.\n'+e);
		}
		finally{}
	}


var sending_chat_message=false;

function sendChatMessage(){
	//alert("pas 1-: "+RequestID);
	if(RequestID==0){
		if(currentTAB && currentTAB.uid)
			RequestID = currentTAB.uid;
		else return;
	}

		var message=$('input_ta').value;
		$('input_ta').value='';

		if(message==''){
	  		return false;
	  	}


				var addr=BASE_URL+'/ajax/messaging/sendmessage.php';
				var parameters='rcpt_uid='+RequestID+'&message='+encode(message)+'&is_chat=1';

				var myAjax = new Ajax.Request(addr,
									{
										method:'post',
										parameters:parameters,
										onFailure: systemError,
										onComplete: messageSent
									});

				sending_chat_message = true;

}

function messageSent(request_sendmsg) {

	if (request_sendmsg.readyState == 4) {
		var htmlDoc = request_sendmsg.responseText;

		if(htmlDoc!='success') {
			currentTAB.append("<div style='margin:1px;'><i><font color=#FF0000>error sending message</font></i>");
		}

		sending_chat_message = false;
		delete request_sendmsg;

	}
}

function startChat() {
	stopQueries=0;
	getChatNewMessagesUsers();
	getChatUserMessages();
}

function showChatWindow(){
	//Element.show('instant_messaging');
	centerWindow('instant_messaging');
	if($('instant_messaging').style.display=='none')
	{
		Element.show('instant_messaging');
		createCookie('chat_window_state','opened',2);
		createCookie('global_chat_window_state','opened',2);
		stopListRequest=0;
		stopQueries=0;
		stopNewMsgNoRefresh=1;
		getChatNewMessagesUsers();
		getChatUserMessages();

	}
	/*if(self.pngFix) {
		if(chatpngsFixed==false){
			pngFix();
			chatpngsFixed=true;
		}
	}*/
}


function hideChatWindow(){
	//Element.hide('instant_messaging');
	Element.hide('instant_messaging');
	stopListRequest=1;
	stopQueries=1;
	stopNewMsgNoRefresh=0;
	refreshNewMsgsNo();
	eraseCookie('chat_window_state');
	eraseCookie('global_chat_window_state');
}

var ChatWindow = Class.create();

ChatWindow.prototype = {

	initialize: function(userID,userName){
		//debugOUT("Adding "+userID);
		this.uid=userID;
		this.user=userName;
		this.is_online=null;

		with (this) new Insertion.Bottom('chat_boxes',"<div id='chat_box_"+uid+"' name='chat_box_"+uid+"' class='Hidden'>Started chat with "+user+"</div>");

		/*with (this) $('chat_boxes').innerHTML = $('chat_boxes').innerHTML + "<div id='chat_box_"+uid+"' name='chat_box_"+uid+"' class='Hidden'>"+user+"</div>";*/

		/*with (this) new Insertion.Bottom('tabs',"<td><div id='tab_"+uid+"' name='tab_"+uid+"' class='tab'><a href='javascript:;' onclick='TABS["+TABS.length+"].showChatBox();'>"+user+"</a> <a href='javascript:;' onclick='TABS["+TABS.length+"].hideTab();' class='smallLink'>[close]</a></div></td>");
		*/
		//alert($('tabs').innerHTML);
		//alert("Req before: "+RequestID);
		//var newCell = $('tabs').insertCell(0);
		//alert("req: "+RequestID+"\n"+$('tabs').innerHTML);
		var x=$('tabs_table').rows[0]
		var y=x.insertCell(0)
		with (this) y.innerHTML = "<div id='tab_"+uid+"' name='tab_"+uid+"' class='tab'><a href='javascript:;' onclick='TABS["+TABS.length+"].showChatBox();'>"+user+"</a> <a href='javascript:;' onclick='TABS["+TABS.length+"].hideTab();' class='smallLink'><img src=\""+BASE_URL+"/images/close.gif\" border=\"0\" alt=\"Close\"></a></div>";

		showedTabs++;


		if(TABS.length==0){
			this.showChatBox();
		//alert('Showing~');
		}

		this.saveInCookie();


	},

	hideTab: function(){

		Hide('tab_'+this.uid);
		this.hideChatBox();
		showedTabs--;

		if(showedTabs<1)
			hideChatWindow();
		//else if(currentTAB==this)
		//	TABS[0].showChatBox();

		this.deleteFromCookie();
	},

	showChatBox: function (){
		document.getElementById('tab_'+this.uid).childNodes[0].style.fontWeight='';
		if(currentTAB)
			currentTAB.hideChatBox();

		Show("chat_box_"+this.uid);

		if($("tab_"+this.uid).style.display=='none'){
			Show("tab_"+this.uid);
			showedTabs++;
			this.saveInCookie();

		}
		//Show("tab_"+this.uid);

		//alert("unselecting "+currentTAB.uid);
		if(currentTAB && currentTAB.uid && currentTAB.uid!=this.uid){

			//alert('unmarking '+currentTAB.uid);
			Element.classNames('tab_'+currentTAB.uid).set("tab");

		}
		currentTAB=this;
		Element.classNames('tab_'+this.uid).set("selected");
		debugOUT("setting to: "+this.uid);
		RequestID=this.uid;
		debugOUT("REQ to: "+RequestID);
		updateScroll();
		createCookie('current_user_chat',this.uid,2);


	},
	hideChatBox: function() {
		Hide("chat_box_"+this.uid);
	},
	highlight: function () {
		$('tab_'+this.uid).childNodes[0].style.fontWeight='bold';
		if($("tab_"+this.uid).style.display=='none'){
			Show("tab_"+this.uid);
			showedTabs++;


		}
		//alert('highli '+this.uid);

	},
	append: function(string) {
		new Insertion.Bottom('chat_box_'+this.uid,string);
	},
	saveInCookie: function() {
		saveUserInCookie(this.uid,this.user);

	},
	deleteFromCookie: function() {

		var chat_user_lists = readCookie('chat_user_list');
		var array1 = chat_user_lists.split('|');
		var array2;
		createCookie('chat_user_list','',2);
		for(i=0;i<array1.length;i++){
			array2 = array1[i].split(',');
			userID = array2[0];
			username = array2[1];

			if(userID && username && userID!=this.uid){
				saveUserInCookie(userID,username);
			}


		}

		//alert(readCookie('chat_user_list'));
	}

};

function saveUserInCookie(uid,user) {
		var chat_user_lists = readCookie('chat_user_list');
		createCookie('chat_user_list',chat_user_lists+"|"+uid+","+user,2);
	}


function getChatNewMessagesUsers() {
	/* retrieves list of users from whom there are new messages and highlights the specified tabs, or adds new ones*/

	if(stopQueries!=1)
	setTimeout("getChatNewMessagesUsers();",(speed));




	if (requesting_list_chat_messages || stopListRequest==1) {
		return false;
	}

	var addr=BASE_URL+'/ajax/messaging/getnewmessagesxml.php';

	var myAjax = new Ajax.Request(addr,
									{
										method:'get',
										onComplete: processUserList,
										onFailure: systemError
									});


	requesting_list_chat_messages = true;

}

function processUserList(request_list_msg) {

		try{
			if (request_list_msg.readyState == 4) {
					requesting_list_chat_messages = false;
				if(request_list_msg.status == 200) {
					var htmlDoc = request_list_msg.responseText;
					//document.getElementById('text_div').innerHTML =  "<pre>"+htmlDoc+"</pre>";
					//document.getElementById('status').innerHTML = '';
					requesting_list_chat_messages = false;
					//delete request_msg;

			var the_object = eval('(' + htmlDoc + ')');
					//alert(the_object);
					//alert(the_object.messages.message[0].id+" "+the_object.messages.message[0].content);
					//return;
				//var new_msgs = new Array();

				if(the_object && the_object.messages){
				var messages = the_object.messages;

				for (var i=0;i<messages.length-1;i++) {
				//	var nextitem = new_msgs.length;
				//	new_msgs[nextitem] = new Array();
					uid = messages[i].uid;
					username = messages[i].username;

					auxTAB = isInTabs(uid);
					if(auxTAB==false) {
						TABS[TABS.length]=new ChatWindow(uid,username);
						auxTAB=TABS[TABS.length-1];
					}
					if(auxTAB!=currentTAB)
						auxTAB.highlight();
				}



			}




			}else {
				debugOUT('Request error.');
				}

		}
		}
	catch(e){
		// caught an error
		debugOUT('Response failed.\n'+e);
	}
	finally{}
}

function tryTAB(uid, username){
	/*checks if the tab with the dates exists, if not creates it and focuses it*/
	thisTAB=isInTabs(uid);
	if(thisTAB==false){
		TABS[TABS.length]=new ChatWindow(uid,username);

		thisTAB=isInTabs(uid);
	}
	 thisTAB.showChatBox();

	 debugOUT("REQ2 to: "+RequestID);
}

function requestUsernameId(username){
	/* creates an ajax request to retrieve a username's id and then add's the user to the chat box and selects it*/
	if(username && username!=""){
		var addr=BASE_URL+'/ajax/check_username_id.php';
		var params = 'rcpt_username='+username;
		var myAjax = new Ajax.Request (addr, {
										method:'post',
										parameters:params,
										onSuccess: addUserToChatWindow,
										onFailure: systemError
										});
		Element.update('user_chat_add_status','Seeking username ...');
		}

	}

	function addUserToChatWindow(request) {
		/* the onSuccess function for the username id request from server, will add the new user to the chat box*/
		if(request.responseText==""){
			return;
		}
		var myArray = request.responseText.split(',');
		userId=myArray[0];
		userName=myArray[1];
		if(userId=='invalid' || !userName || !userId){
			Element.update('user_chat_add_status',"Username not found.");
		} else if(userId=='yourself') {
			Element.update('user_chat_add_status',"Can't chat with yourself.");
		} else
		 {

			addUserChatTab(userId,userName);
			if($('instant_messaging').style.display=='none')
				showChatWindow();

			Element.update('user_chat_add_status','');
			$('chatuser').value='';
			showHide('chat_input_popup');
		}
	}


	  function panRightTabs(howMuch) {
	  	/* sliding the tab lists to right*/
	  	for(i=0;i<howMuch;i++){
			setTimeout( "moveTabsRight();", i*3);
		}
	  }

	  function moveTabsRight(){
	  	$('tabs_parent').scrollLeft+=1;
	  }

	  function panLeftTabs(howMuch) {
	  	/* sliding the tab lists to left*/
	  	for(i=0;i<howMuch;i++){
			setTimeout( "moveTabsLeft();", i*3);
		}
	  }

	  function moveTabsLeft(){
	  	$('tabs_parent').scrollLeft-=1;
	  }



function OnUnloadFunc() {
	debugOUT("unload detected");
	//if(RequestID!=null)
	if(blurred==false) {
		blurred=true;
		Old_RequestID=RequestID;
		RequestID=0;
		stopListRequest=1;
	}
}
//window.onunload = OnUnloadFunc;
//window.onclose = eraseCookie('chat_window_state');
/*(window.onclose = inchidere;
document.onclose = inchidere;(/)(/)()*/
//window.onblur = OnUnloadFunc;

function inchidere(){
	alert('closing');
}

function OnFocusFunc() {
	if(blurred) {
		debugOUT("FOCUS-EVENT: "+Old_RequestID);

		if(Old_RequestID!=null)
			RequestID=Old_RequestID;

		stopListRequest=0;
		blurred=false;
	}
}

function tryToShowChatWindow(){
	/* shows the chat window depending on the state of the cookie, if the chat window is opened elsewhere it will not show*/
	if(readCookie('global_chat_window_state')=="opened")
		alert("The chat window is allready opened in another window.");
	else showChatWindow();
}
function unloadFunc(){
	eraseCookie('global_chat_window_state');
	if(self.GMap2){
		GUnload();
	}
	/*if(self.savePositions){
		if(!layoutSaved){
		if(confirm("You did not save the page layout, whould you like to save the changes?")){
			savePositions();
			//alert('saved!');
			}
		}
	}*/
}

function InputEnter(event)
{

	var code = event.keyCode

	switch (code)
	{
	case 13:
	//alert(event.keyCode)
			sendChatMessage();
			return false;
		break;
	}
}

