var AMEWS_CHAT_AUTOFETCH_FREQUENCY = 5000; // ms

var currentTab = null;
var loaded = false; // Initial load done or not

var xmlHttpPost; // For AJAX POST requests
var xmlHttpFetch; // For AJAX GET requests
var autoFetcher; // For the timer automatically making requests to get new chat messages

var amews_chat_lastChatMsg = []; // Remember last chat msg id received for each chatroom
var amews_chat_rooms = []; // List of all rooms currently in

/** GENERAL FUNCTIONS **/

// Wait for window to load
if (window.addEventListener) { // W3C standard
  	window.addEventListener('load', startChat, false); // NB **not** 'onload'
} 
else if (window.attachEvent) { // Microsoft
  	window.attachEvent('onload', startChat);
}

// Init AJAX
function GetXmlHttpObject() {
	var xmlHttpPost=null;

	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttpPost=new XMLHttpRequest();
	}catch (e) {
		//Internet Explorer
		try {
			xmlHttpPost=new ActiveXObject("Msxml2.xmlHttpPost");
		}catch (e) {
			xmlHttpPost=new ActiveXObject("Microsoft.xmlHttpPost");
		}
	}
	
	return xmlHttpPost;
}

// Generic AJAX GET-request
function loadURL(url,callback) {
	xmlHttpFetch=GetXmlHttpObject();
	if (xmlHttpFetch==null) {
		alert ("Browseren understøtter ikke AJAX")
		return;
	}
	xmlHttpFetch.onreadystatechange=callback;
	xmlHttpFetch.open("GET",url,true);
	xmlHttpFetch.send(null);
}

// Generic AJAX POST-request
function postURL(url,callback,postdata) {
	xmlHttpPost=GetXmlHttpObject();
	if (xmlHttpPost==null) {
		alert ("Browseren understøtter ikke AJAX")
		return;
	}
	
	xmlHttpPost.open("POST", url, true);

	//Send the proper header information along with the request
	xmlHttpPost.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttpPost.setRequestHeader("Content-length", postdata.length);
	xmlHttpPost.setRequestHeader("Connection", "close");
	
	xmlHttpPost.onreadystatechange = callback;
	xmlHttpPost.send(postdata);
}


// Getting current filename - used for url's for AJAX requests
function getFile() {
	var url = self.location.href;
	var lastSlash = url.lastIndexOf("/");
	var firstQuestionMark = url.indexOf("?");
	if(firstQuestionMark == -1)
	{
		firstQuestionMark = url.length;
	}
	var fileName = url.substring(lastSlash + 1, firstQuestionMark);
	return fileName;
}

// Called when browser is ready for starting the chat
function startChat() {
	activateFields(false);
	
	// Join chat
	var postdata = "";
	postURL(getFile() + "?amews-chat=true&action=joinChat", joinChatResult, postdata);
}

function endChat() {
	activateFields(false);
	activateAutoFetcher(false);
}

/** -END- GENERAL FUNCTIONS **/

/** ----------------------- **/


/** PURE GUI **/

function addTab(id, txt) {
	// Add the tab
	var div = document.getElementById('amews_chat_rooms');
	var newTab = document.createElement('div');
	newTab.setAttribute('class', 'amews_chat_tab active');
	newTab.setAttribute('id', 'amews_chat_room_'+id);
	newTab.setAttribute('onclick', 'switchTab('+id+');');
	newTab.appendChild(document.createTextNode(txt));
	div.appendChild(newTab);
	
	// Add the message window
	div = document.getElementById('amews_chat_msgWins');
	newTab = document.createElement('div');
	newTab.setAttribute('class', 'amews_chat_msgWin');
	newTab.setAttribute('id', 'amews_chat_msgWin'+id);
	div.appendChild(newTab);
	
	// Add the users window
	div = document.getElementById('amews_chat_users');
	newTab = document.createElement('div');
	newTab.setAttribute('class', 'amews_chat_usersWin');
	newTab.setAttribute('id', 'amews_chat_usersWin'+id);
	div.appendChild(newTab);
	
	// Hide current tab instead
	if ( currentTab != null ) {
		document.getElementById('amews_chat_usersWin'+currentTab).style.display = 'none';
		document.getElementById('amews_chat_msgWin'+currentTab).style.display = 'none';
		document.getElementById('amews_chat_room_'+currentTab).setAttribute('class', 'amews_chat_tab');
	}
	
	// New tab in focus
	currentTab = id;
}

function removeTab(id) {
	// TODO: Select other tab
	// Update arrays
	
	document.getElementById('amews_chat_usersWin'+id).remove();
	document.getElementById('amews_chat_msgWin'+id).remove();
	document.getElementById('amews_chat_room_'+id).remove();
}

function switchTab(id) {
	document.getElementById('amews_chat_usersWin'+currentTab).style.display = 'none';
	document.getElementById('amews_chat_msgWin'+currentTab).style.display = 'none';
	document.getElementById('amews_chat_room_'+currentTab).setAttribute('class', 'amews_chat_tab');
	currentTab = id;
	document.getElementById('amews_chat_usersWin'+id).style.display = 'block';
	document.getElementById('amews_chat_msgWin'+id).style.display = 'block';
	document.getElementById('amews_chat_room_'+id).setAttribute('class', 'amews_chat_tab active');
}


function activateFields(opt) { // Disables critical fields if opt = false
	if ( opt ) {
		document.getElementById('amews_chat_sendBtn').disabled = "";
		document.getElementById('amews_chat_msg').disabled = "";
		document.getElementById('amews_chat_room').disabled = "";
	}else{
		document.getElementById('amews_chat_sendBtn').disabled = "true";
		document.getElementById('amews_chat_msg').disabled = "true";
		document.getElementById('amews_chat_room').disabled = "true";
	}
}


function writeMsgWin(html,id) {
	var scroll = false;
	var theWin = document.getElementById('amews_chat_msgWin'+id);
	if ( theWin.scrollTop == (theWin.scrollHeight - theWin.offsetHeight) ) scroll = true;
	theWin.innerHTML += html;
	if ( scroll ) theWin.scrollTop = (theWin.scrollHeight - theWin.offsetHeight);
}

function writeError(html) {
	var scroll = false;
	for ( var i = 0; i < amews_chat_rooms.length; i++ ) {
		var theWin = document.getElementById('amews_chat_msgWin'+amews_chat_rooms[i]);
		if ( theWin.scrollTop == (theWin.scrollHeight - theWin.offsetHeight) ) scroll = true;
		theWin.innerHTML += "<span class=\"amews_chat_error\">" + html + "</span><br/><br/>";
		if ( scroll ) theWin.scrollTop = (theWin.scrollHeight - theWin.offsetHeight);
	}
}


function joinChatRoom_select(room) {
	if ( room == "" ) return;
	joinChatRoom(room);
	document.getElementById('amews_chat_room').selectedIndex = 0;
}

function addUser(roomid,id,name,status) {
	// Add the user to list
	if ( document.getElementById('amews_chat_user_'+roomid+'_'+id) != null ) return; // ignore if already added
	var div = document.getElementById('amews_chat_usersWin'+roomid);
	var newUser = document.createElement('div');
	newUser.setAttribute('class', 'amews_chat_user');
	newUser.setAttribute('id', 'amews_chat_user_'+roomid+'_'+id);
	//newUser.setAttribute('onclick', 'switchTab('+id+');');
	newUser.appendChild(document.createTextNode(name));
	div.appendChild(newUser);
}

function removeUser(roomid,id) {
	var user = document.getElementById('amews_chat_user_'+roomid+'_'+id);
	if ( user != null ) user.remove();
}

/** -END- PURE GUI **/

/** ----------------------- **/


function joinChatResult() {
	if (xmlHttpPost.readyState==4 || xmlHttpPost.readyState=="complete") {
		if ( xmlHttpPost.responseText != "<!--DENIED-->" ) {
			// Joined OK
			var res = xmlHttpPost.responseText;
			var splmain = res.split("<!---->");
			var spl = splmain[0].split("<!>");

			amews_chat_rooms[amews_chat_rooms.length] = spl[0];
			amews_chat_lastChatMsg[spl[0]] = -1;
			addTab(spl[0], spl[1]);

			// Add users
			for ( var i = 1; i < splmain.length; i++ ) { // Ignore first - det er room info
				var info = splmain[i].split("<!>");
				addUser(spl[0],info[0], info[1], info[2]);
			}
			
			fetchChat(); // Do first fetch, continue fetching automatically
			if ( loaded == false ) { // Don't activate if already loaded
				activateAutoFetcher(true);
			}
		}else{
			// Joined DENIED
			alert("Der opstod en fejl i forsøget på at komme ind i chatrummet");
		}
	}
}


var amews_chat_cnt = 0; // Used to allow unexpected delays

// Fetch new data for chat
function fetchChat() {
	if ( xmlHttpFetch != null ) { // If active fetch request
		// Postpone 4 times, then abort and start new fetch
		if ( amews_chat_cnt != 4 ) { amews_chat_cnt++; return; }
		try {
			xmlHttpFetch.abort();
			xmlHttpFetch = null;
		}catch(e){
			
		}
	}
	amews_chat_cnt = 0; // Reset postpone counter
	
	var roomsstr = ""; // String specifying which rooms you want updates for
	for ( var i = 0; i < amews_chat_rooms.length; i++ ) { // Build string from array of rooms (room1,room2,...,roomN)
		if ( roomsstr != "" ) roomsstr += ",";
		roomsstr += amews_chat_rooms[i];
	}
	
	// Build string specifying for each room what the latest seen msg id is (&latestID_1=1234&latestID_3=4321...)
	var latestIDstr = ""; 
	for ( var i = 0; i < amews_chat_rooms.length; i++ ) {
		latestIDstr += "&latestID_"+amews_chat_rooms[i]+"="+amews_chat_lastChatMsg[amews_chat_rooms[i]];
	}
	
	if ( loaded == false ) latestIDstr += "&first=true"; // Specify whether or not this is first fetch (get all msg)

	// Request URL with data strings just created
	// (amews-chat=true is for wordpress to include chat script)
	loadURL(getFile() + "?amews-chat=true&action=chatFetch&rooms="+roomsstr+latestIDstr, fetchChatResult);
}

function fetchChatResult() { // Used for callback when new data has been fetched
	if (xmlHttpFetch.readyState==4 || xmlHttpFetch.readyState=="complete") { // Only react on the state "completed" callback
		var res = xmlHttpFetch.responseText; // Result
		var spl = res.split("<!---->"); // Split data (when more than one piece of data is fetched, it is separated with <!---->)
		if ( res != "" ) { // Proceed only if new data was actually received
			for ( var i = 0; i < spl.length; i++ ) {
				var splsingle = spl[i].split("<!>"); // Each data block consists of multiple information, split by <!>
				
				// TODO: ISSUES hvis flere rum på engang - flere posts (huh?)
				if ( document.getElementById('amews_chat_msgWin'+splsingle[2]) == null ) { // If not currently exists room-tab which data was intended for, ignore
					continue;
				}
				
				amews_chat_lastChatMsg[splsingle[2]] = parseInt(splsingle[0]); // Update last chat id
				
				// Handle message according to type
				if ( splsingle[1] == "SERVERNOTICE" ) { 
					// SERVER NOTICE/OPERATION
					handleServerNoticeOp(splsingle);
				}else if ( splsingle[1] == "SELFNOTICE" ) {
					// Information generated for a single purpose (kicked etc.)
					handleSelfNotice(splsingle);
				}else{
					// User message	- add received chat message to appropriate tab
					var username = splsingle[3];
					var msg = splsingle[5];
					writeMsgWin("[" + splsingle[4] + "] <b>" + username + "</b>:<br/>" + msg + "<br/><br/>", splsingle[2]);	
				}
			}
		
		}
		
		for ( var i = 0; i < amews_chat_rooms.length; i++ ) {
			// After joined chat, last chat id initialized by -1.
			// Should now have retrieved any data from that room, so if still uninitialized, set to 0.
			// See chat-fetch file for usage
			if ( amews_chat_lastChatMsg[amews_chat_rooms[i]] == -1 ) amews_chat_lastChatMsg[amews_chat_rooms[i]] = 0;
		}
		
		xmlHttpFetch = null; // Reset fetcher
		if ( loaded == false ) { // If first fetch completed
			// Activate all fields for user input, and focus the chat message textbox
			loaded = true;
			activateFields(true);
			document.getElementById('amews_chat_msg').focus();
		}
	}
}



// Automatically fetch new data with interval determined by AMEWS_CHAT_AUTOFETCH_FREQUENCY
function activateAutoFetcher(opt) { // opt determines whether it should activate (true) or deactivate (false) autofetch
	if ( opt ) {
		amews_chat_cnt = 0;
		if ( autoFetcher != null ) clearInterval(autoFetcher); // Clear possible old timer
		autoFetcher = setInterval("fetchChat();", AMEWS_CHAT_AUTOFETCH_FREQUENCY); // Start interval
	}else{
		if ( autoFetcher != null ) clearInterval(autoFetcher); // Clear if not already cleared
		autoFetcher = null;
		if ( xmlHttpFetch != null ) { // Abort possible active fetch request
			try {
				xmlHttpFetch.abort();
				xmlHttpFetch = null;
			}catch(e){
				
			}
		}
	}
}



function handleServerNoticeOp(msg) {
	if ( msg[5] == "2" ) { // Joined info
		addUser(msg[2],msg[7],msg[6],msg[8]);
		writeMsgWin("[" + msg[3] + "] "+msg[6]+" er trådt ind i dette chat-rum<br/><br/>", msg[2]);
	}else if ( msg[5] == "3" ) { // Left info
		removeUser(msg[2],msg[7]);
		writeMsgWin("[" + msg[3] + "] "+msg[6]+" har forladt dette chat-rum (Årsag: "+msg[4]+")<br/><br/>", msg[2]);
	}else if ( msg[5] == "4" ) { // Kicked info
		removeUser(msg[2],msg[7]);
		writeMsgWin("[" + msg[3] + "] "+msg[6]+" blev smidt ud af chatrummet (Årsag: "+msg[4]+")<br/><br/>", msg[2]);
	}
}

function handleSelfNotice(msg) {
	if ( msg[5] == "4" ) { // Kicked info
		writeError("---- Du blev smidt ud af chatten (Årsag: "+msg[4]+") ----<br/>Genstart evt. chatten for at komme ind igen.<br/><br/>", msg[2]);
		endChat();
	}
}



// Send new chat message
function amews_chat_sendmsg() {
	activateFields(false); // Deactivate fields until sent to avoid several attempts interrupting each other
	var postdata = "amews_chat_msg=" + encodeURIComponent(document.getElementById('amews_chat_msg').value)
				+ "&amews_chat_room=" + encodeURIComponent(currentTab);
	postURL(getFile() + "?amews-chat=true&action=postMsg", postResult, postdata);
}

// Called when new chat message was succesfully posted
function postResult() {
	if (xmlHttpPost.readyState==4 || xmlHttpPost.readyState=="complete") { // Only react on state "complete"
		if ( loaded == false ) return; // Ignore results until chat is loaded - just in case
		var res = xmlHttpPost.responseText; // Split reply as when fetching
		var spl = res.split("<!---->");
		if ( res != "" ) { // Denied if no reply text
			
			for ( var i = 0; i < spl.length; i++ ) {
				var splsingle = spl[i].split("<!>");
				// Write own message to chat-tab when confirmed posted (now - server accepted it)
				var username = splsingle[1];
				var msg = splsingle[3];
				writeMsgWin("[" + splsingle[2] + "] <b>" + username + "</b>:<br/>" + msg + "<br/><br/>", splsingle[0]);	
			}
		}
		
		document.getElementById('amews_chat_msg').value = ""; // Empty input textbox, reactivate and focus.
		activateFields(true);
		document.getElementById('amews_chat_msg').focus();
	}
}


function joinChatRoom(room) { // Called by GUI
	if ( document.getElementById('amews_chat_room_'+room) != null ) { // If already joined, switch to that tab
		switchTab(room);
	}else{ // Otherwise, post request to join room
		// Look here if issue arises (joining and posting new chat msg at the same time)
		var postdata = "amews_chat_room=" + encodeURIComponent(room);
		postURL(getFile() + "?amews-chat=true&action=joinChat", joinChatResult, postdata);
	}
}




/** ------------------- **/

/** OLD CODE **/

// OLD ROOM SWITCH
/** 
function switchRoom(room) {
	activateFields(false);
	activateAutoFetcher(false);
	var postdata = "&amews_chat_room=" + encodeURIComponent(document.getElementById('amews_chat_room').value);
	postURL(getFile() + "?amews-chat=true&action=switchRoom", switchRoomResult, postdata);
}

function switchRoomResult() {
	if (xmlHttpPost.readyState==4 || xmlHttpPost.readyState=="complete") {
		if ( xmlHttpPost.responseText == "OK" ) {
			writeMsgWin("<b>Rum-skift er nu udført</b><br/><br />");
		}else{
			writeMsgWin("<b>Der opstod en fejl ved rum-skift</b><br/>");
		}
		activateAutoFetcher(true);
		activateFields(true);
	}
	
}
**/


