// Ajax Chat
// Copyright Scott Bounds 2006
// http://www.scottbounds.com


function ajaxChat(el){

	this.init = function(){
		var _this = this;
		
		this.messages = document.createElement('div');
		this.messages.className = 'chatMessages';
		this.chat.appendChild(this.messages);
		
		this.controls = document.createElement('div');
		this.controls.className = 'chatControls';
		this.chat.appendChild(this.controls);
		
		this.input = document.createElement('input');
		this.input.type = 'text';
		this.input.maxlength = '1000';
		this.input.className = 'msgInput';
		this.controls.appendChild(this.input);
		
		this.button = document.createElement('input');
		this.button.type = 'button';
		this.button.value = ' SEND ';
		this.button.className = 'btn';
		this.controls.appendChild(this.button);
		
		this.add('sys','Connecting to chat server...');
		
		this.ajaxPoll = new ajaxRequest();
		this.ajaxPost = new ajaxRequest();
		
		this.ajaxPoll.success = _this.getInitial;
		setTimeout(function(){_this.ajaxPoll.get('/chat_query.php?init=1');},1000);
		this.setChatTimeout();
	}
	
	this.getInitial = function(){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		var i, xml, settings, messages, _this = this;
		
		this.add('sys','Connected. Receiving messages.');
		
		xml = this.ajaxPoll.responseXML;
		
		//set settings
		settings = xml.getElementsByTagName('settings');
		this.refreshTime = 5000;
		if (settings.length > 0){
			for (i=0;i<settings[0].childNodes.length;i++){
				switch (settings[0].childNodes[i].tagName.toLowerCase()){
					case 'refresh':
						this.refreshTime = settings[0].childNodes[i].firstChild.nodeValue*1000;
						break;
				}
			}
		}
		
		//set recent messages
		messages = xml.getElementsByTagName('message');
		if (messages.length > 0){
			this.lastReceived = messages[messages.length-1].getAttribute('id');
			this.showMessages(messages,0);
		}
		
		//activate polling
		this.ajaxPoll.success = _this.poll;
		this.pollInterval = setInterval(function(){_this.ajaxPoll.get('/chat_query.php?last='+_this.lastReceived);},this.refreshTime);
		
		//activate posting
		addListener(this.button,'click',_this.post,false);
		addListener(this.input,'keyup',_this.post,false);
	}
	
	this.poll = function(){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		
		xml = this.ajaxPoll.responseXML;
		messages = xml.getElementsByTagName('message');
		if (messages.length > 0){
			this.lastReceived = messages[messages.length-1].getAttribute('id');
			this.showMessages(messages,0);
		}
	}
	
	this.post = function(e){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		var _this = this; e=fixE(e);
		
		//check event
		if (e.type != 'click' && (e.type == 'keyup' && e.keyCode != 13)) return;
		if (this.input.value == '') return;
		//if (this.ajaxPost.busy) return;
		
		this.ajaxPost.success = _this.postResponse;
		this.ajaxPost.get('/chat_query.php?post=1','POST','msg='+escape(this.input.value));
		this.input.value = '';
		this.input.focus();
		this.setChatTimeout();
	}
	this.postResponse = function(){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		var xml, response, messages, success = false; _this = this; 
		
		xml = this.ajaxPost.responseXML;
		response = xml.getElementsByTagName('post');
		if (response.length > 0){
			if (response[0].firstChild.nodeValue == 'success'){
				success = true;
				
				messages = xml.getElementsByTagName('message');
				if (messages.length > 0) this.showMessages(messages,0);
			}
		}
	}
	
	this.showMessages = function(messages,i){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		
		var _this = this;
		
		if (messages.length > i){
			this.add('msg',messages[i].firstChild.nodeValue);
			setTimeout(function(){_this.showMessages(messages,i+1);},10);
		}
		
	}
	
	this.add = function(type,text){
		var msg = document.createElement('div');
		msg.className = type;
		msg.innerHTML = text;
		this.messages.appendChild(msg);
		
		this.messages.scrollTop = this.messages.scrollHeight;
		
		return msg;
	}
	this.clear = function(){
		this.messages.innerHTML = '';	
	}
	
	this.setChatTimeout = function(){
		_this = this;
		this.timeoutTimer = clearTimeout(this.timeoutTimer);
		this.timeoutTimer = setTimeout(function(){_this.timeout();},1000*60*15);
	}
	this.timeout = function(){
		_this = this;
		
		this.pollInterval = clearInterval(this.pollInterval);
		this.timeoutTimer = clearTimeout(this.timeoutTimer);
		
		this.clear();
		var msg = this.add('sys','Session timed out. Click Here to re-join chat room.');
		addListener(msg,'click',_this.rejoin,false);
		
		removeListener(this.button,'click',_this.post,false);
		removeListener(this.input,'keyup',_this.post,false);
		//this.pollInterval = setInterval(function(){_this.ajaxPoll.get('/chat_query.php?last='+_this.lastReceived);},this.refreshTime);
	}
	
	this.rejoin = function(e){
		if(this != arguments.callee._oScope) return arguments.callee.apply(arguments.callee._oScope, arguments); //check scope
		
		_this = this;
		removeListener(getEventTarget(e),'click',_this.rejoin,false);
		
		this.clear();
		this.add('sys','Connecting to chat server...');
		
		this.ajaxPoll.success = _this.getInitial;
		setTimeout(function(){_this.ajaxPoll.get('/chat_query.php?init=1');},1000);
		this.setChatTimeout();
	}
	
	//set scope references
	this.getInitial._oScope = this;
	this.poll._oScope = this;
	this.post._oScope = this;
	this.postResponse._oScope = this;
	this.showMessages._oScope = this;
	this.rejoin._oScope = this;

	this.chat = $(el);
	this.init();
}