var currentUser;
var recipientSel;
$(document).ready(function() {	
	dwr.engine.setActiveReverseAjax(true);
	
	recipientSel = document.getElementById('recipient');
	
	$('#loader').show();
	$('#login').hide();
	ChatService.getCurrentUser(onGetCurrentUser);

	$('#loginFrm').submit(function() {

		nick = $.trim($("#nick").val());
		if(nick.length > 0) {
			$('#loader').show();
			ChatService.login(nick, onLogin);
		} else {
			alert('Please enter nick');
		}

		return false;
	});
	
	$('#chatFrm').submit(function() {
		text = $.trim($("#text").val());

		if(text.length > 0) {
			$('#loader').show();
			
			disableOrEnableChatFrm(false);
			
			message = new Object();
			message.message = text;
			
			recipientUserId = recipientSel.options[recipientSel.selectedIndex].value;
			if(recipientUserId > 0) {
				message.recipient = {userId: recipientUserId, nick: recipientSel.options[recipientSel.selectedIndex].text};
			}
			ChatService.addMessage(message, afterAddMessage);
		} else {
			alert('Please enter message');
		}

		return false;
	});
	
	$('#logout').click(function() {
		$('#loader').show();
		ChatService.logout(onLogout);
		return false;
	});
});

function onGetCurrentUser(user) {
	if(user == null) $('#login').show();
	addCurrentUserInfo(user, false);
}

function onLogin(user) {
	addCurrentUserInfo(user, true);
}

function onLogout(result) {
	document.location.reload();
}

function addCurrentUserInfo(user, alertOnUserNull) {
	$('#loader').hide();

	if(user == null) {
		if(alertOnUserNull) alert('Error during login');
	} else {
		currentUser = user;
		
		$('#logout').before(currentUser.nick + '[userId=' + currentUser.userId + '] ');
		
		$('#login').hide();
		$('#chat').show();
		
		DWREngine.beginBatch();
		ChatService.getOnlineUsers(onGetOnlineUsers);
		ChatService.getMessages(onReceiveMessages);
		DWREngine.endBatch();
	}
}

function afterAddMessage() {
	$('#loader').hide();
	$('#text').val('');
	disableOrEnableChatFrm(true);
}

function onReceiveMessages(messages) {
	for(i = 0; i < messages.length; i++) {
		addMessage(messages[i]);
	}
}

function addMessage(message) {
	txt = '<div>[' + formatDate(message.time) + '] ' + message.sender.nick + (message.recipient != null ? (' -> ' + message.recipient.nick):'') + ': ' + message.message;
	txt += '</div>';
	$('#messages').prepend(txt);
}

function onGetOnlineUsers(users) {
	for(i = 0; i < users.length; i++) {
		addUser(users[i]);
	}
}

function addUser(user) {
	if(user.userId == currentUser.userId) return;
	
	newOption = new Option(user.nick, user.userId);		
	try { recipientSel.add(newOption, recipientSel.options[recipientSel.options.length]); }
	catch(ex) { recipientSel.add(newOption); }	
}

function removeUser(user) {
	for(i = 0; i < recipientSel.options.length; i++) {
		if(recipientSel.options[i].value == user.userId) {
			recipientSel.options[i] = null;
			return;
		}
	}
}

function formatDate(time) {
	_date = new Date();
	_date.setTime(parseInt(time));
	h = _date.getHours();
	m = _date.getMinutes();
	s = _date.getSeconds();
	return (h < 10 ? '0':'') + h + ":" + (m < 10 ? '0':'') + m + ":" + (s < 10 ? '0':'') + s;
}

function disableOrEnableChatFrm(enable) {
	$('#chatFrm input, #chatFrm select').each(function() {
		$(this).attr('disabled', !enable);
	});
}