﻿$(function () {
	$('#chkOverride').click(function () {
		if (this.checked) {
			$('#txtChannel').css({ 'display': 'inline' });
			$('.ddlChannels').css({ 'display': 'none' });
		}
		else {
			$('#txtChannel').css({ 'display': 'none' });
			$('.ddlChannels').css({ 'display': 'inline' });
		}
	});

	var ticks = new Date();
	var lastTicks = ticks.getTime();

	$('.txtUserName').val(localStorage.getItem('UserName'));

	$(window).bind('beforeunload', function () {
		PageMethods.RemoveUser(localStorage.getItem('UserName'), localStorage.getItem('Channel'), OnRemoveUser, OnRemoveUserFail);
	});

	function OnRemoveUser() {
		send(localStorage.getItem('UserName') + ' has left, and I bet they didn\'t even say goodbye.');
	}

	function OnRemoveUserFail() {
		alert(error.get_message());
	}

	loadChannels();

	function loadChannels() {
		PageMethods.LoadChannels(OnLoadChannels, OnLoadChannelsFail);
	}

	function OnLoadChannels(data) {
		$('.ddlChannels').html();

		for (var i = 0; i < data.length; i++) {
			$('.ddlChannels').append('<option value="' + data[i].replace('Channel', '') + '">' + data[i].replace('Channel', '') + '</option>');
		}
	}

	function OnLoadChannelsFail(error) {
		alert(error.get_message());
	}

	$('#txtMessage').keypress(function (e) {
		if (e.keyCode == 13) {
			e.preventDefault();
			sendMessage();
		}
	});

	$('#btnLogin').click(function () {
		IsUserNameDuplicate();
	});

	$('#btnSend').click(function () {
		sendMessage();
	});

	function sendMessage() {
		send('[' + localStorage.getItem('UserName') + ']: ' + $('#txtMessage').val());
		$('#txtMessage').val('');
	}

	function IsUserNameDuplicate() {
		PageMethods.HasUser($('.txtUserName').val(), getChannel(), OnIsUserNameDuplicate, OnIsUserNameDuplicateFail);
	}

	function OnIsUserNameDuplicate(data) {
		if (!data) {
			login();
		}
		else {
			$('#lblError').html('Sorry, user name is taken.');
		}
	}

	function OnIsUserNameDuplicateFail(error) {
		alert(error.get_message());
	}

	function getChannel() {
		var returnValue = '';

		if ($('#chkOverride').is(':checked')) {
			returnValue = $('#txtChannel').val();
		}
		else {
			returnValue = $('.ddlChannels').val();
		}

		if (returnValue == '' || returnValue == undefined || returnValue == null) {
			returnValue = 'Default';
		}

		returnValue = 'The Lounge';

		return returnValue;
	}

	function login() {
		if (localStorage) {
			localStorage.clear();
			localStorage.setItem('Channel', getChannel());
			localStorage.setItem('UserName', $('.txtUserName').val());

			$('#divLogin').css({ 'display': 'none' });
			$('#divChat').css({ 'display': 'inline' });

			send('Welcome ' + localStorage.getItem('UserName'));

			setInterval(function () {
				pollForInformation();
			}, 10000);
		}
		else {
			alert('Please use a browser that supports localStorage. You know, something up to date.');
		}
	}

	function pollForInformation() {
		PageMethods.Poll(localStorage.getItem('Channel'), lastTicks, OnPoll, OnPollFail);
	}

	function OnPoll(data) {
		var dt = new Date();
		lastTicks = dt.getTime();

		if (data != null) {
			for (var i = 0; i < data.Messages.length; i++) {
				$('#divMessages').append(data.Messages[i].Content + '<br />');
			}

			$('#divUsers').html('');
			for (var i = 0; i < data.Users.length; i++) {
				$('#divUsers').append(data.Users[i] + '<br />');
			}
		}

		$("#divMessages").prop({ scrollTop: $("#divMessages").prop("scrollHeight") });
	}

	function OnPollFail(error) {
		alert('Oops, something bad happened: ' + error.get_message());
	}

	function send(message) {
		var dt = new Date();

		PageMethods.SendMessage(message, localStorage.getItem('Channel'), dt.getTime(), OnSend, OnSendFail);
	}

	function OnSend(data) {
		pollForInformation();
	}

	function OnSendFail(error) {
		alert('Oops, something bad happened: ' + error.get_message());
	}
});
