/*
 * Chat functions (using jquery).
 * 
 * Note: the head-tag of the html-page must contain a variable "chat" which is an instance of chatObject.
 */

function chatObject ()
{

	this.visibility = 0;
	this.timer = null;
	this.isInitialized = false;

	this.init = function ( visibility )
	{
		this.fetchChatMessages();
		
		this.setVisibility( visibility );
		
		$("form#chat_send_form").submit(function(event){
			try {
				chat.sendChatMessage();
			}
			catch ( error ) {
				var chatMessages = $("#chat_messages");
				var output = "<i>Es ist ein Fehler aufgetreten";
				if ( error )
					output += " (" + error + ")";
				output += ".</i><br>";
				chatMessages.append( output );
				try { chat.scrollToBottom( chatMessages ); }
				catch ( error2 ) {}
			}
			return false;
		});
		
		this.isInitialized = true;
	}

	this.setVisibility = function ( visibility )
	{
		if ( this.visibility != visibility || !this.isInitialized ) {
			this.visibility = visibility;
			if ( visibility == 1 ) {
				var chatDiv = $("#chat");
				chatDiv.removeClass( "hidden" );
				chatDiv.removeClass( "minimized" );
				this.scrollToBottom( $("#chat_messages") );
				if ( this.isInitialized )
					$.post("chatserver.php",{ action: "showchat", visibility: this.visibility });
			}
			else if ( visibility == 2 ) {
				var chatDiv = $("#chat");
				chatDiv.removeClass( "hidden" );
				chatDiv.addClass( "minimized" );
				this.scrollToBottom( $("#chat_messages") );
				if ( this.isInitialized )
					$.post("chatserver.php",{ action: "showchat", visibility: this.visibility });
			}
			else if ( visibility == 0 ) {
				$("#chat").addClass( "hidden" );
				if ( this.isInitialized )
					$.post("chatserver.php",{ action: "hidechat" });
			}
		}
	}

	this.isScrolledToBottom = function ( element )
	{
		if ( !element || !element[0] )
			return false;
		if ( element[0].scrollHeight - element.scrollTop() == element.outerHeight() )
			return true;
		else
			return false;
	}

	this.scrollToBottom = function ( element )
	{
		var scrollPos = element[0].scrollHeight;
		element.scrollTop( scrollPos );
	}

	this.selectUser = function ( userId )
	{
		var userSelect = $("select#chat_send_to");
		if ( userSelect )
			userSelect.val( userId );
	}

	this.showChatMessages = function ( xml )
	{
		var chatMessages = $("#chat_messages");
		var autoScroll = this.isScrolledToBottom( chatMessages );
		var userId = $("chatuserid", xml).text();
		var chatTimestamp = Number( $("chattimestamp", xml).text() );
		$("message", xml).each(function(id) {
			var message = $("message", xml).get(id);
			var timestamp = $("timestamp", message).text();
			if ( timestamp > $("#chat_last_timestamp").val() )
				$("#chat_last_timestamp").val( timestamp );
			var date = $("date", message).text();
			var from = $("from", message).text();
			var fromName = $("fromName", message).text();
			var to = $("to", message).text();
			var toName = $("toName", message).text();
			var text = $("text", message).text();
			
			var output = "";
			var outputPrefix = "";
			var outputSuffix = "";
			if ( timestamp < chatTimestamp - 600 ) {  // 10 minutes
				outputPrefix += "<span class=\"chat_very_old\">";
				outputSuffix += "</span>";
			}
			else if ( timestamp < chatTimestamp - 300 ) {  // 5 minutes
				outputPrefix += "<span class=\"chat_old\">";
				outputSuffix += "</span>";
			}
			if ( from != userId )
				output += "<a class=\"chat_from\" href=\"javascript:chat.selectUser(" + from + ");\">";
			else
				output += "<span class=\"chat_from\">";
			if ( from == userId && to != 0 ) {
				output += "Du fl&uuml;sterst ";
				if ( toName )
					output += toName + " zu";
				else
					output += "? zu";
			}
			else if ( fromName )
				output += fromName;
			else
				output += "?";
			if ( from != userId )
				output += "</a>";
			else
				output += "</span>";
			if ( to == userId )
				output += " fl&uuml;stert dir zu";
			output += ": " + "<span title=\"Nachricht vom " + date + "\">" + text + "</span>";
			if ( to != 0 )
				output = "[" + output + "]";
			output = outputPrefix + output + outputSuffix + "<br>";
			
			chatMessages.append( output );
		});
		// scroll to bottom of chat messages:
		if ( autoScroll || !this.isInitialized ) {
			this.scrollToBottom( chatMessages );
		}
	}

	this.showChatUsers = function ( xml )
	{
		var usersSelect = $("select#chat_send_to");
		var selectedValue = usersSelect.val();
		var haveSelection = false;
		usersSelect.empty();
		usersSelect.append( "<option value=''>alle</option>" );
		$("user", xml).each(function(id) {
			var user = $("user", xml).get(id);
			var userId = $("userid", user).text();
			var userName = $("username", user).text();
			var firstName = $("firstname", user).text();
			var lastName = $("lastname", user).text();
			
			if ( userId == selectedValue )
				haveSelection = true;
			
			usersSelect.append( "<option value='" + userId + "'>" + userName + "</option>" );
		});
		
		if ( haveSelection )
			usersSelect.val( selectedValue );
	}

	this.sendChatMessage = function ( event )
	{
		$.post("chatserver.php",{  
			action: "sendmessage",
			to: $("select#chat_send_to").val(),  
			message: $("#chat_send_message").val(),  
			timestamp: $("#chat_last_timestamp").val()
		}, function(xml) {
			chat.showChatMessages(xml);
			$("#chat_send_message").val('');
		});
		return false;
	}

	this.fetchChatMessages = function ()
	{
		$.post("chatserver.php",{
			action: "getmessages",
			timestamp: $("#chat_last_timestamp").val()
		}, function(xml) {
			chat.showChatMessages(xml);
			chat.showChatUsers(xml);
		});
		this.timer = setTimeout( function(){ chat.fetchChatMessages(); }, 4000 );
	}
}
