// settings
var messages = {id:false, delay:6666};
var online = {id:false, delay:33333};
var player = false;
function shrink(img) {
	img.ow = $(img).width();
	if (img.ow * 2 > ws) {
		img.oh = $(img).height();
		img.width = img.ow;
		img.height = img.oh;
		img.width = img.ow / (img.ow / (ws / 2));
		img.height = img.height / (img.ow / (ws / 2));
		if (img.parentNode.nodeName != 'A') {
			img.onclick = ri;
			img.title = img.src;
			img.className = 'resized';
		}
	}
};
function chatAddMessage(row) {
	if ($("#m" + row.message_id).length == 0) {
		if (row.user_id != 32) {
			$("<li/>").attr("id", "m" + row.message_id).html("[" + row.message_time + "] <b>" + row.username + "</b>: " + row.message).css('display', 'none').appendTo("#messages").fadeIn("slow");
		}
		else {
			$("<li/>").attr("id", "m" + row.message_id).html("<i>[" + row.message_time + "] " + row.username + ": " + row.message + "</i>").css('display', 'none').appendTo("#messages").fadeIn("slow");
		}
		// scroll down
		_$('left').scrollTop = _$('left').scrollHeight;
		// shrink images in message
		$("#m" + row.message_id).find('img').each(function(){
			if (!this.complete) {
				this.onload = function() {
					shrink(this);
				};
			}
			else {
				shrink(this);
			}
		});
		// play sound
		if (player && row.message.substring(0, 6) == '!sound') {
			var mp3 = 'mp3/links/' + row.message.substring(7) + '.mp3';
			player.plyrLoad(mp3);
			player.plyrPlay(mp3);
		}
	}
}
function emoticon(code) {
	var e = _$('message');
	if (e.createTextRange && e.caretPos) {
		var caretPos = e.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? code + ' ' : code;
		e.focus();
	}
	else {
		e.value += code;
		e.focus();
	}
}
function quote() {
	var s = window.getSelection ? window.getSelection() : (document.getSelection ? document.getSelection() : document.selection.createRange().text);
	if (s) {
		emoticon('[quote]' + s + '[/quote]\n');
	}
	else {
		alert('Markiere einen Text auf der Seite und versuche es noch einmal');
	}
	return false;
}
// get flash object (from swfobject)
function getObjectById(objectIdStr) {
	var r = null;
	var o = _$(objectIdStr);
	if (o && o.nodeName == "OBJECT") {
		if (typeof o.SetVariable != "undefined") {
			r = o;
		}
		else {
			var n = o.getElementsByTagName("object")[0];
			if (n) {
				r = n;
			}
		}
	}
	return r;
}
function chatInit() {
	// get sound player
	player = getObjectById('player');
	// scroll to bottom
	_$('left').scrollTop = _$('left').scrollHeight;
	// get messages by interval
	$.ajaxSetup({cache: false});
	messages['id'] = setInterval(function() {
		$.getJSON("api/chatMessages.php",
			{entry_id:eid},
			function(data){
				if (data.error) {
					alert(data.error);
					return;
				}
				$.each(data, function(i,row){chatAddMessage(row)});
			}
		);
	}, messages['delay']);
	// get online users by interval
	online['id'] = setInterval(function() {
		$.getJSON('api/chatOnlinelist.php',
			function(data){
				if (data.error) {
					alert(data.error);
					return false;
				}
				// delete online list
				$('#online').find('li').each(function(){
					$(this).remove();
				});
				// add users that are online
				$.each(data, function(i,row){
					if ($('#u' + row.user_id).length == 0) {
						if (row.away == 0) {
							$('<li/>').attr('id', 'u' + row.user_id).prepend('<a href="' + escape(row.username) + '-u' + row.user_id + '.htm" target="_blank">' + row.username + '</a>').prependTo('#online');
						}
						else {
							$('<li/>').attr('id', 'u' + row.user_id).prepend('<i><a href="' + escape(row.username) + '-u' + row.user_id + '.htm" target="_blank">' + row.username + '</a></i>').prependTo('#online');
						}
					}
				});
			}
		);
	}, online['delay']);
	// add onmouseover and onclick to smilies
	$("#options").find('img').each(function (){
		$(this).mouseover(function () {
			$(this).css('cursor', 'pointer');
		});
		$(this).click(function () {
			emoticon($(this).attr('title'));
		});
	});
	// submit new message
	$('#chatform').submit(function() {
		var msg = $('#message').val() + ' ';
		var command = msg.substring(0, msg.indexOf(' '));
		switch (command) {
			case '/sounds':
			case '!sounds':
				$.getJSON('json/chatSounds.json',
					function(data){
						// display available mp3s
						var now = new Date();
						var row = {
							user_id:'32',
							username:'MaXBoT',
							message_id:'i' + now.getTime(),
							message_time:(now.getHours() > 9 ? now.getHours() : '0' + now.getHours()) + ':' + (now.getMinutes() > 9 ? now.getMinutes() : '0' + now.getMinutes()),
							message:''
						};
						$.each(data, function(cmd,mp3){
							row.message += mp3 + ': ' + cmd + '<br />\n';
						});
						chatAddMessage(row);
					}
				);
				return false;
				break;
			case '/clear':
			case '!clear':
				// delete messages
				$('#messages').find('li').each(function(){
					$(this).css('display', 'none');
				});
				$('#message').val('');
				return false;
				break;
			case '/quit':
			case '!quit':
			case '/part':
			case '!part':
			case '/logout':
			case '!logout':
				// close chat
				window.close();
				$('#message').val('');
				return false;
				break;
		}
		$.post('api/chatSendMessage.php',
			$('#chatform').serialize(),
			function(data){
				if (data.error) {
					alert(data.error);
					return;
				}
				$('#message').val('');
				$.each(data, function(i,row){chatAddMessage(row)});
			},
			'json'
		);
		return false;
	});
	// fast logout if window has been closed
	if (typeof window.onbeforeunload != 'undefined') {
		window.onbeforeunload = function() {
			$.getJSON("api/chatExit.php",
				{u:uid, entry_id:eid},
				function(data){
					if (data.error) {
						alert(data.error);
					}
				}
			);
		};
	}
}
// set heights
function chatLayoutHeights() {
	$('#left').height($(window).height() - 72);
	$('#right').height($(window).height() - 72);
}
// set heights on resize
$(window).resize(function() {
	chatLayoutHeights();
});
