// run loop to check if chat request initiated
// if so then display chat panel

function chat_check(user_id) {
	ajaxFunction(user_id);
	setTimeout("chat_check(" + user_id + ")",10000);
}

// code based on http://www.tizag.com/ajaxTutorial/ajax-javascript.php
function ajaxFunction(user_id){
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			// convert json array into js array
			//alert(ajaxRequest.responseText);
			var text = eval("(" + ajaxRequest.responseText + ")");
			var friend_nice = text['friend_nice'];
			//if (friend_nice == '') friend_nice = text['friend_user'];
			if (text['msg'] && (!document.getElementById('fba-chat')) ) {
				if (text['msg'] == 'request') {
					document.getElementById('chat-alert').innerHTML = "<span class=\"boldgrey\">CHAT REQUEST:</span> " + friend_nice + " wants to <a href=\"/community/chat?friend=" + text['friend_ID'] + "&friend_name=" + friend_nice + "\">chat with you</a>.<a onclick=\"denyRequest(" + user_id + ", " + text['friend_ID'] + ")\"><img id=\"chat-close\" src=\"/images/menus/sub-menu/chat-close.png\" width=\"12\" height=\"12\" alt=\"Close\"/></a>";
				} else {
					document.getElementById('chat-alert').innerHTML = "<span class=\"boldgrey\">CHAT CONFIMATION:</span> " + friend_nice + " is ready to <a href=\"/community/chat?friend=" + text['friend_ID'] + "&friend_name=" + friend_nice + "\">chat with you</a>.<a onclick=\"denyRequest(" + user_id + ", " + text['friend_ID'] + ")\"><img id=\"chat-close\" src=\"/images/menus/sub-menu/chat-close.png\" width=\"12\" height=\"12\" alt=\"Close\"/></a>";
				}
				document.getElementById('chat-alert').style.display = 'block';
				
			} else {
				document.getElementById('chat-alert').style.display = 'none';
				document.getElementById('chat-alert').innerHTML = "";
			}
		}
	}
	var queryString = "?user=" + user_id;
	ajaxRequest.open("GET", "/scripts/fba-chat/chat-check.php" + queryString, true);
	ajaxRequest.send(); 
}
