﻿var userScrollPosition = -1;
var lastMessageId = 0;
var needToUpdateOccupantsList = false;
var timeoutId;
var minTimerInterval;
var maxTimerInterval;
var timerStep
var timerInterval;
var isAdmin = false;
var currentChatName = '';
var chatLoginUrl = '';
var errorCount = 0;
var maxErrorCount;
var roomInstanceCount;
var messageTextBoxWatermarkText;
var postBack = false;
var audibleNotifications = true;
var notificationSound;
function setChatTimer()
{
	var sendButton = $get("SendButton");
	if (sendButton.disabled == false)
		timeoutId = setTimeout("updateConversation()", timerInterval);
}
function stopChatTimer()
{
	clearTimeout(timeoutId);
}
function increaseTimerInterval()
{
	if (timerInterval < maxTimerInterval)
		timerInterval += timerStep;
}
function resetTimerInterval()
{
	timerInterval = minTimerInterval;
}
function onTimeOut(error)
{
	if (errorCount >= maxErrorCount)
		appendMessage("errorMessage", "The operation timed out.");
	else
		errorCount += 1;
	setChatTimer();
}
function onPageLoad()
{
	// set sound at the start of this method so it's not as visible
	// to the user if we need to toggle the sound on/off image
	if (isAdmin)
		useSound = getChatRoomSoundSetting();
	else
	{
		var useSound = getCookie("sound");
		if (useSound != undefined)
		{
			if (useSound == 'false')
				toggleSounds();
		}
	}

	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
	updateOccupants();
	timerInterval = minTimerInterval;

    // Initialize the message text box with the fonts selected by the user.
    var msgTextBox = $get('MessageTextBox');
    if (msgTextBox)
    {
        msgTextBox.style.fontFamily = messageFontFamily;        
		msgTextBox.style.fontSize = messageFontSize;
	    msgTextBox.style.color = messageFontColor;
    }

	setChatTimer();
}
function pageLoaded(sender, args)
{
	postBack = false;

	if (sender == undefined)
		return;
	if (sender._postBackSettings == undefined)
		return;
	if (sender._postBackSettings.sourceElement == undefined)
		return;
		
	switch(sender._postBackSettings.sourceElement.id)
	{
		case "Settings1_OkButton":
			validator = $get("Settings1_SettingsCustomValidator");
			if (validator.style.display == 'none')
				showPopup('none');
			break;
		case "CancelLink":
			validator = $get("Settings1_SettingsCustomValidator");
			validator.style.display = 'none';
			showPopup('none');
			break;
		case "Invite1_OkButton":
			validator = $get("Invite1_InviteUserCustomValidator");
			var validator2 = $get("Invite1_CaptchaCustomValidator");
			if (validator.style.display == 'none' && validator2.style.display == 'none')
				showPopup('none');
	}
	
	var panels = args.get_panelsUpdated();
	for(i=0;i<panels.length;i++)
	{
		if (panels[i].id == "Settings1_SettingsUpdatePanel")
		{
			updateOccupants();
			break;
		}
	}
}
function endRequest(sender, args)
{
    var error = args.get_error();
    if (error)
    {
		alert("The operation failed. Please try again.");
        args.set_errorHandled(true);
    }
}
function scrollConversation()
{
	var conversationDiv = $get('ConversationDiv');
	if (userScrollPosition != -1)
		conversationDiv.scrollTop = userScrollPosition;
	else
		conversationDiv.scrollTop = conversationDiv.scrollHeight - conversationDiv.clientHeight;
}
function MessageTextBox_OnKeyDown(e)
{
	if(e.which || e.keyCode)
	{
		if ((e.which == 13) || (e.keyCode == 13))
		{
			sendMessage();
			e.returnValue = false;
		}
	}
}
function appendMessage(messageClass, message, userName, messageTime, fontFamily, fontSize, fontColor)
{
	var newSpan = document.createElement("span");
	newSpan.setAttribute("class", messageClass);
	
	var messageSpan = null;

	var style = newSpan.getAttribute("style");
	if (messageClass == "systemMessage")
	{
		if (style != undefined && style != null) // IE
			style.fontWeight = "bold";
			
    	newSpan.innerHTML = message + '<br/>';			
	}
	else if (messageClass == "errorMessage")
	{		
		if (style != undefined && style != null) // IE
			style.color = "Red";
			
    	newSpan.innerHTML = message + '<br/>';			
	}
	else // User message
	{
    	newSpan.innerHTML = '[' + userName + ']: ' + messageTime;        
	    messageSpan = document.createElement("span");
	    messageSpan.setAttribute("class", messageClass);    	
	    messageSpan.style.fontFamily = fontFamily;
	    messageSpan.style.fontSize = fontSize + 'px';
        messageSpan.style.color = fontColor;	    
        messageSpan.style.paddingBottom = '10px';
        messageSpan.innerHTML = message;      
    }
    
	var conversationDiv = document.getElementById('ConversationDiv');
	conversationDiv.appendChild(newSpan);
	if (messageSpan != null)
	    conversationDiv.appendChild(messageSpan);
	
	scrollConversation();
}
function clearMessages()
{
	var conversationDiv = $get('ConversationDiv');
	while(conversationDiv.childNodes.length > 0)
		conversationDiv.removeChild(conversationDiv.firstChild);
	userScrollPosition = -1;
}
function updateConversation()
{
	stopChatTimer();
	var conversationDiv = $get('ConversationDiv');
	if (conversationDiv.scrollTop >= (conversationDiv.scrollHeight - conversationDiv.clientHeight))
		userScrollPosition = -1;
	else
		userScrollPosition = conversationDiv.scrollTop;
	GDChat.WebApp.ChatSystem.GetChatMessages2(domain, lastMessageId, getChatMessages_Success, getChatMessages_Error);
}
function getChatMessages_Success(e)
{
	errorCount = 0;
	needToUpdateOccupantsList = false;
	
	if (e != undefined && e.length > 0)
	{
		var notificationTrigger = false;
		var lastMessageDateTime = null;
		for(i=0;i<e.length;i++)
		{
			switch(e[i].MessageType)
			{
				case 0: // user
				    lastMessageDateTime = new Date(e[i].MessageTime);
					appendMessage("userMessage", e[i].Message, e[i].UserName, getFormattedTime(lastMessageDateTime), e[i].FontType, e[i].FontSize, e[i].FontColor);
					if (e[i].UserName != currentChatName)
						notificationTrigger = true;
					break;
				case 1: // system
					needToUpdateOccupantsList = true;
					appendMessage("systemMessage", e[i].Message);
					if (e[i].UserName != currentChatName)
						notificationTrigger = true;
					break;
				case 2: // clear
					clearMessages();
					break
				case 3: // room instance count change
					if (isAdmin)
						roomInstanceCount = e[i].Message;
					if (e[i].Message == 0)
						onChatRoomClosed();
					break;
				case 4: // rename
					needToUpdateOccupantsList = true;
					appendMessage("systemMessage", e[i].UserName + ' has been renamed to ' + e[i].Message);
					if (e[i].UserName != currentChatName)
						notificationTrigger = true;
					break;
				case 5: // remove
					if (e[i].UserName == currentChatName)
					{
						appendMessage("systemMessage", 'You have been removed from the chat room by the administrator. You are no longer able to send or receive messages.');
						clearOccupants();
						disableChatClient();
						GDChat.WebApp.ChatSystem.SetSessionRemoved();
					}
					else
					{
						needToUpdateOccupantsList = true;
						appendMessage("systemMessage", e[i].UserName + ' has been removed from the conversation.');
					}
					if (e[i].UserName != currentChatName)
						notificationTrigger = true;
					break;
				default:
					appendMessage("userMessage", e[i].Message);
					if (e[i].UserName != currentChatName)
						notificationTrigger = true;
					break;
			}
			lastMessageId = e[i].MessageId;
		}
		if (notificationTrigger) { notify(); }
		if (lastMessageDateTime) { updateLastMessageReceiveStatus(lastMessageDateTime); }
		scrollConversation();
		if (needToUpdateOccupantsList == true)
			updateOccupants();
		resetTimerInterval();
	}
	else
	{
		increaseTimerInterval();
	}
	setChatTimer();
}
function getChatMessages_Error(error)
{
	if (error._timedOut == true)
	{
		onTimeOut(error);
		return;
	}
	if (error._message == "The chat room does not exist.")
	{
		onChatRoomClosed();
		return;
	}
	if (error._message == "Not in chat room.")
	{
		onNotInChatRoom();
		return;
	}
	if (error._message == "Authentication failed.")
	{
		appendMessage("systemMessage", "The chat room has been closed for system maintenance. You are no longer able to send messages.");
		clearOccupants();
		disableChatClient();
		return;
	}
	if (errorCount >= maxErrorCount)
		appendMessage("errorMessage", "An error occurred while retrieving messages.");
	else
		errorCount += 1;
	increaseTimerInterval();
	setChatTimer();
}
function onChatRoomClosed()
{
	appendMessage("systemMessage", "The chat room has been closed. You are no longer able to send messages.");
	clearOccupants();
	disableChatClient();
}
function onNotInChatRoom()
{
	appendMessage("systemMessage", "You are no longer in the chat room. You are no longer able to send or receive messages.");
	clearOccupants();
	disableChatClient();
}
function disableChatClient()
{
	var messageInput = $get("MessageTextBox");
	messageInput.value = '';
	messageInput.disabled = true;
	$get("SendButton").disabled = true;
	if (isAdmin == true)
	{
		var link = $get("settingsLink");
		link.disabled = true;
		link = $get("inviteLink");
		link.disabled = true;
		link = $get("clearLink");
		link.disabled = true;
		link = $get("removeLink");
		link.disabled = true;
	}
}
function updateOccupants()
{
	GDChat.WebApp.ChatSystem.GetChatRoomOccupants(getChatRoomOccupants_Success, getChatRoomOccupants_Error);
}
function getChatRoomOccupants_Success(e)
{
	errorCount = 0;
	clearOccupants();
	
	if (e.length == 0)
		return;

	if (!isAdmin)
	{
		var foundMyName = false;
		for(i=0;i<e.length;i++)
		{
			if (e[i] == currentChatName)
			{
				foundMyName = true;
				continue;
			}
		}
		if (foundMyName == false)
		{
			onNotInChatRoom();
			return;
		}
	}
	
	var span = $get("UserCountSpan");
	if (e.length == 1)
		span.innerHTML = '<strong>1 person</strong><br/> in this room';
	else
		span.innerHTML = '<strong>' + e.length + ' people</strong><br/> in this room';
	
	var occupantsDiv = $get('occupantsDiv');
	var newSpan;
	for(i=0;i<e.length;i++)
	{
		newSpan = document.createElement("span");
		newSpan.setAttribute("class", "occupantName");
		newSpan.innerHTML = e[i] + '<br/>';
		newSpan.setAttribute("title", e[i]);
		occupantsDiv.appendChild(newSpan);
	}
	
	if (isAdmin)
	{
		var removableUsersDiv = $get("RemovableUsersListDiv");
		var settings_removableUsersDiv = $get("Settings_RemovableUsersListDiv");
		
		if (removableUsersDiv != undefined)
		{
			var text;
			if(e.length > 1)
				text = "Select the visitors you want to remove from the chat room."
			else
				text = "There are no visitors to remove from the chat room."

			span = $get("RemoveUsersText");
			if (span != undefined)
				span.innerHTML = text;
			span = $get("Settings_RemoveUsersText");
			if (span != undefined)
				span.innerHTML = text;
			
			for(i=0;i<e.length;i++)
			{
				if (e[i] != currentChatName)
				{
					var innerHTML = "<input type='checkbox' id='" + e[i] + "' name='" + e[i] + "' />" + e[i] + "<br/>";
					
					newSpan = document.createElement("span");
					newSpan.setAttribute("class", "removableUser");
					newSpan.innerHTML = innerHTML;
					removableUsersDiv.appendChild(newSpan);

					if (settings_removableUsersDiv != undefined)
					{
						newSpan = document.createElement("span");
						newSpan.setAttribute("class", "removableUser");
						newSpan.innerHTML = innerHTML;
						settings_removableUsersDiv.appendChild(newSpan);
					}
				}
			}
		}
	}
}
function getChatRoomOccupants_Error(error)
{
	if (error._timedOut == true)
	{
		onTimeOut(error);
		return;
	}
	if (error._message == "Not in chat room.")
	{
		onNotInChatRoom();
		return;
	}
	if (errorCount >= maxErrorCount)
		appendMessage("errorMessage", "An error occurred while updating the occupants list.");
	else
		errorCount += 1;
	increaseTimerInterval();
	setChatTimer();
}
function clearOccupants()
{
	var span = $get("UserCountSpan");
	span.innerHTML = '<strong>0 people</strong><br/> in this room';

	var occupantsDiv = $get('occupantsDiv');
	while(occupantsDiv.childNodes.length > 0)
		occupantsDiv.removeChild(occupantsDiv.firstChild);
	var removableUsersDiv = $get('RemovableUsersListDiv');
	if (removableUsersDiv != undefined)
	{
		while(removableUsersDiv.childNodes.length > 0)
			removableUsersDiv.removeChild(removableUsersDiv.firstChild);
	}
	removableUsersDiv = $get('Settings_RemovableUsersListDiv');
	if (removableUsersDiv != undefined)
	{
		while(removableUsersDiv.childNodes.length > 0)
			removableUsersDiv.removeChild(removableUsersDiv.firstChild);
	}
}
function sendMessage()
{
	var message = $get("MessageTextBox").value;
	if (message != messageTextBoxWatermarkText)
	{
		stopChatTimer();
		GDChat.WebApp.ChatSystem.SendMessageWithCustomFont(message, messageFontFamily, messageFontSize, messageFontColor, sendMessage_Success, sendMessage_Error);
	}
}
function sendMessage_Success(e)
{
	errorCount = 0;
	var messageInput = $get("MessageTextBox");
	messageInput.value = '';
	messageInput.focus();
	updateConversation();
}
function sendMessage_Error(error)
{
	if (error._message == "Not in chat room.")
	{
		onNotInChatRoom();
		return;
	}
	else
		appendMessage("errorMessage", "An error occurred while sending your message. Please try again.");
}
function sendClearCommand()
{
	$get("MessageTextBox").focus();
	GDChat.WebApp.ChatSystem.SendClearCommand(sendClearCommand_Success, sendClearCommand_Error);
}
function sendClearCommand_Success()
{
	errorCount = 0;
	updateConversation();
}
function sendClearCommand_Error(error)
{
	if (error._message == "Not in chat room.")
	{
		onNotInChatRoom();
		return;
	}
	appendMessage("errorMessage", "An error occurred while sending your message. Please try again.");
}
function removeUsers()
{
	var div = $get("RemovableUsersListDiv");
    var usersToRemove = new Array(0);
		
	for(i=0;i<div.childNodes.length;i++)
	{
		var span = div.childNodes[i];
		if (span.firstChild.checked)
			usersToRemove.push(span.firstChild.id);
	}
	if (usersToRemove.length > 0)
		GDChat.WebApp.ChatSystem.RemoveVisitors(usersToRemove, removeUsers_Success, removeUsers_Error);
	showPopup('none');
}
function removeUsers_Success()
{
	errorCount = 0;
}
function removeUsers_Error(error)
{
	if (error._message == "Not in chat room.")
	{
		onNotInChatRoom();
		return;
	}
	appendMessage("errorMessage", "An error occurred while removing visitors. Please try again.");
}
function cancelInvite()
{
	var textbox = $get("Invite1_ToTextBox");
	textbox.value = "";
	textbox = $get("Invite1_FromTextBox");
	textbox.value = "";
	textbox = $get("Invite1_CaptchaTextBox");
	textbox.value = "";

	var validator = $get("Invite1_InviteUserCustomValidator");
	validator.style.display = 'none'
	validator = $get("Invite1_CaptchaCustomValidator");
	validator.style.display = 'none'
	showPopup('none');
}
function showPopup(popupToShow)
{
	var removeUsersPopup = $get("RemoveUsersDiv");
	var invitePopup = $get("InviteDiv");
	var settingsPopup = $get("SettingsDiv");
	var fontPopup = $get("FontDiv");
	
	switch(popupToShow)
	{
		case "none":
			invitePopup.style.display = 'none';
			settingsPopup.style.display = 'none';
			removeUsersPopup.style.display = 'none';
			fontPopup.style.display = 'none';
			$get("MessageTextBox").focus();
			break;
		case "remove":
			invitePopup.style.display = 'none';
			settingsPopup.style.display = 'none';
			fontPopup.style.display = 'none';			
			removeUsersPopup.style.display = 'block';
			break;
		case "invite":
			removeUsersPopup.style.display = 'none';
			settingsPopup.style.display = 'none';
			invitePopup.style.display = 'block';
			$get("Invite1_ToTextBox").focus();
			break;
		case "settings":
			removeUsersPopup.style.display = 'none';
			invitePopup.style.display = 'none';
			fontPopup.style.display = 'none';			
			settingsPopup.style.display = 'block';
			$get("Settings1_ScreenNameTextBox").focus();
			break;
        case "font":
			removeUsersPopup.style.display = 'none';
			settingsPopup.style.display = 'none';
			invitePopup.style.display = 'none';
			fontPopup.style.display = 'block';			
			Sys.UI.DomElement.setLocation(fontPopup, 20, 320);		
			$get('Font1_FontDropDownList').focus();
            break;			
		default:
			invitePopup.style.display = 'none';
			settingsPopup.style.display = 'none';
			removeUsersPopup.style.display = 'none';
			fontPopup.style.display = 'none';	
			break;
	}
}
function leaveChat()
{
	try 
	{
		window.location = chatLoginUrl;
	}
	catch (ex)
	{
	}
}
function checkFocus()
{
	if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Firefox") != -1)
		return document.hasFocus();
	else if (navigator.userAgent.indexOf("Opera") != -1)
		return (document.activeElement.id == "MessageTextBox");
	else return false;
}
function notify()
{
	try
	{
		if (!audibleNotifications) { return; }
		if (checkFocus() == true) { return; }

		var sound = $get('notificationSound');
		sound.Play();
	}
	catch (ex) { }
}
function toggleSounds()
{
	if (audibleNotifications)
	{
		audibleNotifications = false;
		$get("AudibleNotifationsImage").src = "images/chat_vol_off.gif";
	}
	else
	{
		audibleNotifications = true;
		$get("AudibleNotifationsImage").src = "images/chat_vol_on.gif";
	}
	if (isAdmin)
		setChatRoomSoundSetting();
	else
		setCookie("sound", audibleNotifications);
}
function setCookie(name, value)
{
	var date = new Date();
	date.setTime(date.getTime()+(30*24*60*60*1000)); // 30 days
	var expires = "; expires="+date.toGMTString();
	document.cookie = name+"="+value+expires+";path=/";
}
function getCookie(name) {
	var nameEq = name + "=";
	var cookieArray = document.cookie.split(';');
	for(var i=0;i<cookieArray.length;i++) {
		var c = cookieArray[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEq) == 0) return c.substring(nameEq.length,c.length);
	}
	return null;
}
function setChatRoomSoundSetting()
{
	GDChat.WebApp.ChatSystem.SetEnableSoundAlert(audibleNotifications);
}
function getChatRoomSoundSetting()
{
	GDChat.WebApp.ChatSystem.GetEnableSoundAlert(getChatRoomSoundSetting_Success, getChatRoomSoundSetting_Error);
}
function getChatRoomSoundSetting_Success(useSound)
{
	if (!useSound)
		toggleSounds();
}
function getChatRoomSoundSetting_Error(error)
{
}
function getFormattedTime(dateTimeVar)
{
    var hour = dateTimeVar.getHours();
    var ampm = 'AM';
    if (hour > 11)
    {
        hour = hour - 12;
        ampm = 'PM';
    }                
    
    var minute = new String(dateTimeVar.getMinutes());
    // prepend a '0 if it is less than 10.
    if (minute.length == 1)
        minute = '0' + minute;
            
    return hour + ':' + minute + ampm;
}
function getFormattedDate(dateTimeVar)
{
    var month = dateTimeVar.getMonth() + 1;
    
    var year = new String(dateTimeVar.getFullYear());
    
    return month + '/' + dateTimeVar.getDate() + '/' + year.substring(2);
}
function updateLastMessageReceiveStatus(dateTimeVar)
{    
    var statusBox = $get('StatusSpan');
    if (statusBox)
    {
        statusBox.innerHTML = 'Last message received on ' + getFormattedDate(dateTimeVar) + ' at ' + getFormattedTime(dateTimeVar);
    }
}

