function ChatManager() {
	this.chat_sessions = Array();
}
ChatManager.prototype.register_chat_session = function(chat_session) {
		//TODO: initalize chat
		this.chat_sessions.push(chat_session);
}
ChatManager.prototype.get_chat_session_by_key = function(user_key) {
		for (i = 0; i < this.chat_sessions.length; i++) {
	        if(this.chat_sessions[i].user_key==user_key) {
				return this.chat_sessions[i];
			}
	    }
		return null;
}
var chat_manager = new ChatManager();
function ChatSession(){
}
	ChatSession.prototype.user_key=""
	ChatSession.prototype.send_message = function(message) {
		alert("Sending message: "+message)
		new Ajax.Request('/chat/send/message', {
        method: 'post',
        parameters: {
            message: message,
			user_key: this.user_key
        },
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON();
            if (json.success == "yes") {
                alert("chat_sent");
            }
            else if(json.success == "no")  {
                alert("chat_not_sent, unknown reason");
            } else {
				alert("no response")
			}
        },
        onFailure: function(){
            alert('Something went wrong...')
        }
    });
	}

function send_chat(user_key) {
	message = $('chat_entry-'+user_key).value;
	$("chat_area-"+user_key).innerHTML += "<br/>You: "+message;
	chat_manager.get_chat_session_by_key(user_key).send_message(message);
	return false;
}
function start_chat(user_key) {
	chat_session = new ChatSession();
	chat_session.user_key = user_key;
	this.chat_manager.register_chat_session(chat_session);
	create_chat_window(user_key);
}
function create_chat_window(user_key) {
	title = "Chat with User";
	window_html = "<div class=\"title\">" + title + "</div><div class=\"content\"><div class=\"chat_area\" id=\"chat_area-" + user_key + "\">Welcome to Bearded Games chat<br/></div><input class=\"chat_entry\" id=\"chat_entry-" + user_key + "\" type=\"text\" /><input type=\"button\" onclick=\"send_chat('" + user_key + "')\" value=\"Send\" /></div>";
	window_div = document.createElement("div");
	window_div.innerHTML = window_html;
	window_div.className = "window chat";
	window_div.id = "window-chat-"+user_key;
	open_link_xy = $("chat-open-link-" + user_key).viewportOffset();
	window_div.style.right = (document.viewport.getWidth() - open_link_xy.left - 200) + "px";
	window_div.style.bottom = "24px";
	$('chat_windows').appendChild(window_div);
	return false;
}

function poll_chat_server() {
	new Ajax.Request('/chat/poll/messages', {
        method: 'post',
        onSuccess: function(transport){
			alert(transport.responseText);
        },
        onFailure: function(){
            alert('Something went wrong...')
        }
    });
}
//window.setInterval(poll_chat_server, 5*1000);
