/**
 * This javascript will simply check if someone has intiated a chat with this person.
 */
 
 
/* Set how many miliseconds to wait to get new messages */
var updateInterval = 1000;
 


/*####### DO NOT CHANGE ANYTHING BELOW THIS LINE ######## */
 
//Create a XMLHttpRequest object to get and post the chat messages
var xmlHttpCheckChats = createXmlHttpRequestObject();

//This is used to store the Users ID
var userID = 0;

//Initailise the XML Parser Object
parser = new DOMImplementation();

//Initialise the request cache
var cache = new Array();

//Initialise the chat record array
var record = new Array();


/**
 * This function will process the chat response and if there is one or more chat requests then
 * ask the user if they wish to accept
 */
function processChatRequest(){

	if (xmlHttpCheckChats.readyState == 4) {
	
		//Get the response
		var response = xmlHttpCheckChats.responseText;
		//alert(response);
	
		//load the XML into the parser and get the DOMDocument
		var domDoc = parser.loadXML(response);
		
		//get the root node
		var docRoot = domDoc.getDocumentElement();
		
		//Are there any chat elements?
		if(docRoot.getElementsByTagName('chat').length > 0){
			
			//Loop through all the chat elements and ask the user if they wish to accept
			for(i=0; i < docRoot.getElementsByTagName('chat').length; i ++){
			
				//Get the chat element
				var chat = docRoot.getElementsByTagName('chat').item(i);
				
				//Get the chat id
				var chat_id = chat.getElementsByTagName('chat_id').item(0).getFirstChild().getNodeValue();
				
				//Check to see if this is the first time we have seen this chat
				var chatProcessed = false;
				for(var x=0; x < record.length; x++){
					//alert(record[i] + ' = ' + chat_id);
					if(record[i] == trim(chat_id)) { chatProcessed = true; /*alert('TRUE');*/ }
				}
				
				if(chatProcessed == false){
					//This is a new chat convosation
				
					//Add this chat to the chat record
					record.push(trim(chat_id));
					
					//Get the remote user's username
					var remoteUsername = chat.getElementsByTagName('remote_username').item(0).getFirstChild().getNodeValue();
					
					//Ask the user if they wish to accept this convosation
					if(confirm('Would you like to accept a chat inviation from ' + remoteUsername) == true){
						
						//Before we can open the chat window we need to get the rest of the infomation
						
						//Fetch the remote user ID
						var remoteUserID = chat.getElementsByTagName('remote_user_id').item(0).getFirstChild().getNodeValue();
						
						//Open the chat window
						openChat(chat_id,remoteUserID);
						
						// we will check again for new chats
						setTimeout("checkForChat();", updateInterval);
						
						
					} //end if (confirm('Would you like to accept a chat inviations from ' + remoteUsername) == true)
					else{
						//The chat has been rejected
						rejectChat(chat_id);
						
						// we will check again for new chats
						setTimeout("checkForChat();", updateInterval);
					}
					
				}
				else{
					//We have already seen this chat messgae
					
					// we will check again for new chats
					setTimeout("checkForChat();", updateInterval);
				}
				
			
			}// end for (i=0; i < docRoot.getElementsByTagName('chat').length; i ++)
			
		}//end if (docRoot.getElementsByTagName('chat').length > 0)
		else{
		
			// we will check again for new chats
			setTimeout("checkForChat();", updateInterval);
		
		}
		
	} //end if (xmlHttpCheckChats.readyState == 4)

} // end function



/**
 * This function will add a request on to the end of requests to make to the server.
 */
function rejectChat(chatID){

	var params = "function=reject&chatID=" + chatID;
	
	cache.push(params);

}


/**
 * This function will start a chat
 */
function startChat(remoteUserID){
	
	if(remoteUserID > 0){
		openChat(0,remoteUserID);
	}

}



function openChat(chatID,remoteUserID){

	var thenewwwin = window.open('chat_dialog.php?user1_ID=' + userID + '&user2_ID=' + remoteUserID + '&chat_ID=' + chatID,'chat_window_' + chatID,'width=387,height=497,resizable=yes,scrollbars=no,status=yes');
	thenewwwin.focus();

}



/**
 * This function is the same as trim in PHP it removes leading
 * and trailing spaces from the string
 */
function trim(s) {
	
	return s.replace(/(^\s+)|(\s+$)/g, "");
	
}


/**
 * This function will create a connection to the server side script and wait for an XML
 * response which it will then pass on to be processed.
 */
function checkForChat(){

	// only continue if xmlHttpCheckChats isn't void
	if(xmlHttpCheckChats){
		try{
			/* don't start another server operation if such an operation
			is already in progress */
			if (xmlHttpCheckChats.readyState == 4 || xmlHttpCheckChats.readyState == 0){
	
				var params = '';
				
				// if there are requests stored in queue, take the oldest one
				if (cache.length>0) { params = cache.shift(); }
	
				// if the cache is empty, just check for new chats
				else {
					params = "function=chatCheck&userID=" + userID;	
				}
				
				//alert(params);
				
				// call the server page to execute the server-side operation
				xmlHttpCheckChats.onreadystatechange = function() { processChatRequest(); }
				xmlHttpCheckChats.open("POST", 'chat_check.php', true);
				xmlHttpCheckChats.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xmlHttpCheckChats.send(params);
	
			}
			else{
	
				// we will check again for new messages
				setTimeout("checkForChat();", updateInterval);
	
			}
		}
		catch(e){
			alert(e.toString());
		}
	}

}



/**
 * This function initialises this javascript function
 *
 * @Param	Integer		The user ID to use to check for chats
 */
function init(user_ID){

	//Store the users ID
	userID = user_ID;
	
	//Start checking
	checkForChat();

}