
 


ChatSettings.prototype.EXPANDED_BOX_DIFFERENCE = 100;

ChatSettings.prototype.STATE = chatVars.chatState;
ChatSettings.prototype.TOURNAMENT = chatVars.isTournament;
ChatSettings.prototype.ALLOW_CHATTING = true;

ChatSettings.prototype.MAX_MESSAGE_LENGTH;

ChatSettings.prototype._maxMessageSize = false;
ChatSettings.prototype._cookieLifeTime = (36 * 60 * 60 * 24 * 31); 


function ChatSettings() {}


ChatSettings.prototype.getMaxMessageSize = function () {

if (this._maxMessageSize == false) {
this._maxMessageSize = chatController._server.getMaxMessageSize();
}
return this._maxMessageSize;
}


ChatSettings.prototype.getFontSize = function() {
if (undefined == this._cookieFontSize) {
this._cookieFontSize = (chatTools.readCookie('cookieFontSize') ? chatTools.readCookie('cookieFontSize') : 'medium');
}
return this._cookieFontSize;
};
ChatSettings.prototype.setFontSize = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieFontSize', newValue, expdate, '/', null, false);

this._cookieFontSize = newValue;
}


ChatSettings.prototype.getChatareaWidth = function() {
if (undefined == this._cookieChatareaWidth) {
this._cookieChatareaWidth = (chatTools.readCookie('cookieChatareaWidth') ? chatTools.readCookie('cookieChatareaWidth') : 'normal');
}
return this._cookieChatareaWidth;
};
ChatSettings.prototype.setChatareaWidth = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieChatareaWidth', newValue, expdate, '/', null, false);

this._cookieChatareaWidth = newValue;
}


ChatSettings.prototype.getInfoText = function() {
if (undefined == this._infoText) {
this._infoText = (chatTools.readCookie('cookieInfoText') ? chatTools.readCookie('cookieInfoText') : 'friends');
}
return this._infoText;
};
ChatSettings.prototype.setInfoText = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieInfoText', newValue, expdate, '/', null, false);

this._infoText = newValue;
}
ChatSettings.prototype.wantsInfoText = function () {
return this.getInfoText() == 'active';
}
ChatSettings.prototype.wantsInfoTextFriends = function () {
return this.getInfoText() == 'friends';
}


ChatSettings.prototype.getSmileyType = function() {
if (undefined == this._smileyType) {
this._smileyType = (chatTools.readCookie('cookieSmileyType') ? chatTools.readCookie('cookieSmileyType') : 'animated');
}
return this._smileyType;
};
ChatSettings.prototype.setSmileyType = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieSmileyType', newValue, expdate, '/', null, false);

this._smileyType = newValue;
}


ChatSettings.prototype.getStyleSheet = function() {
if (undefined == this._styleSheet) {
this._styleSheet = (chatTools.readCookie('cookieTheme') ? chatTools.readCookie('cookieTheme') : 'standard');
}
return this._styleSheet;
};
ChatSettings.prototype.setStyleSheet = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieTheme', newValue, expdate, '/', null, false);

this._styleSheet = newValue;
}

ChatSettings.prototype.getFontWeight = function() {
if (undefined == this._fontWeight) {
this._fontWeight = (chatTools.readCookie('cookieFontWeight') ? chatTools.readCookie('cookieFontWeight') : 'normal');
}
return this._fontWeight;
};
ChatSettings.prototype.setFontWeight = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieFontWeight', newValue, expdate, '/', null, false);

this._fontWeight = newValue;
}


ChatSettings.prototype.getAvatarsVisible = function() {
if (undefined == this._avatarsVisible) {
this._avatarsVisible = (chatTools.readCookie('cookieAvatarsVisible') ? chatTools.readCookie('cookieAvatarsVisible') : '1');
}
return this._avatarsVisible;
};
ChatSettings.prototype.setAvatarsVisible = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieAvatarsVisible', newValue, expdate, '/', null, false);

this._avatarsVisible = newValue;
}


ChatSettings.prototype.getSoundSettings = function() {
if (undefined == this._soundSettings) {
this._soundSettings = (chatTools.readCookie('cookieSoundSettings') ? chatTools.readCookie('cookieSoundSettings') : '1');
}
return this._soundSettings;
};
ChatSettings.prototype.setSoundSettings = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieSoundSettings', newValue, expdate, '/', null, false);

this._soundSettings = newValue;
}


ChatSettings.prototype.getOldChatSettings = function() {
if (undefined == this._oldChatSettings) {
this._oldChatSettings = (chatTools.readCookie('cookieOldChatSettings') ? chatTools.readCookie('cookieOldChatSettings') : '1');
}
return this._oldChatSettings;
};
ChatSettings.prototype.setOldChatSettings = function (newValue) {
var expdate = chatTools.getUnix() + this._cookieLifeTime;
chatTools.writeCookie('cookieOldChatSettings', newValue, expdate, '/', null, false);

this._oldChatSettings = newValue;
}


ChatSettings.prototype.resetSettings = function () {

this.setSmileyType('animated');
this.setInfoText('friends');
this.setFontSize('medium');
this.setChatareaWidth('normal');
this.setFontWeight('normal');

this.setAvatarsVisible('1');
this.setOldChatSettings('1');
this.setSoundSettings('1');
this.setStyleSheet('standard');
}




ChatSettings.prototype.isSingleplayerChat = function() {
return (this.STATE == 1);
};


ChatSettings.prototype.isMultiplayerChat = function() {
return (this.STATE == 2);
};


ChatSettings.prototype.isInstantMessenger = function() {
return (this.STATE == 3);
};


ChatSettings.prototype.isTournament = function() {
return (this.TOURNAMENT == true);
};

ChatSettings.prototype.chattingAllowed = function () {
return (this.ALLOW_CHATTING == true);
}

ChatSettings.prototype.playIMSounds = function () {
return (this.getSoundSettings() == '1');
}







function ChatTools() {}


ChatTools.prototype.getHashcode = function(str) {
var i = 0;
var hash = 0;
for (i = 0; i < str.length; i++) {
hash = (hash * 31 + str.charCodeAt(i)) & 0xffffffff;
}
return Math.abs(hash);
}


ChatTools.prototype.compareStrings = function (firstString, nextString) {


var first = '' + firstString;
var next = '' + nextString;


if (first.length > 0 && next.length > 0) {
first = jQuery.trim('' + first).toLowerCase();
next =  jQuery.trim('' + next).toLowerCase();
}

if (first.length > 0 && next.length > 0) {




if (first.charAt(0) < next.charAt(0) ) {return -1;}
if (first.charAt(0) > next.charAt(0) ) {return 1;}
if (first.charAt(1) < next.charAt(1) ) {return -1;}
if (first.charAt(1) > next.charAt(1) ) {return 1;}
if (first.charAt(2) < next.charAt(2) ) {return -1;}
if (first.charAt(2) > next.charAt(2) ) {return 1;}
return 0;




for (var index = 0; index < first.length; index++) {


if (index >= next.length) {return 1;}

if (first.charAt(index) < next.charAt(index) ) {return -1;}
if (first.charAt(index) > next.charAt(index) ) {return 1;}
}
return 0;
}
return 0;
}


ChatTools.prototype.compareIntegers = function (first, next) {

if (first < next) {
return -1;
} else if (first > next) {
return 1;
}
return 0;
}


ChatTools.prototype._encodeString = function (theMessage) {

return theMessage;


}


ChatTools.prototype.encodeEmails = function (str) {
return str.replace(/([^\s]+@[^\s]+(\.[^\s]+)+)/, "<a href=\"mailto:$1\">$1</a>");
}


ChatTools.prototype.numberFormat = function (nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];

if (x.length > 1) {
x2 = '.' + x[1];
} else {
x2 = '';
}

var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}


ChatTools.prototype.isNumeric = function (string) {
var validchars = '0123456789.';
var isnumber = true;
var character;

for (var i = 0; i < string.length && isnumber; i++) {
character = string.charAt(i);
if (validchars.indexOf(character) == -1) {
isnumber = false;
}
}
return isnumber;
}



ChatTools.prototype.inArray = function (theArray, theValue) {
for (var i = 0; i < theArray.length; i++) {
if (theValue == theArray[i]) {
return true;
}
}
return false;
}


ChatTools.prototype.swapArrayValues = function (list, index1, index2) {
var tmp = list[index1];
list[index1] = list[index2];
list[index2] = tmp;
}


ChatTools.prototype.readCookie = function (cookieName) {
var theCookie= document.cookie;
var cookieName = cookieName + "=";
var cLength = theCookie.length;
var startAt= 0;
while (startAt < cLength) {
var end = startAt + cookieName.length;
if (theCookie.substring(startAt, end) == cookieName) {
var last = theCookie.indexOf (";", end);
if (last == -1) {
last = cLength;
}
return unescape(theCookie.substring(end, last));
}
startAt = theCookie.indexOf(" ", startAt) + 1;
if (startAt == 0) {
break;
}
}
return null;
}


ChatTools.prototype.writeCookie = function (name, value) {

var arguments = ChatTools.prototype.writeCookie.arguments;
var noOfArguments = ChatTools.prototype.writeCookie.arguments.length;

var expires = (noOfArguments > 2) ? arguments[2] : null;
var path= (noOfArguments > 3) ? arguments[3] : null;
var dom = (noOfArguments > 4) ? arguments[4] : null;
var secure = (noOfArguments > 5) ? arguments[5] : false;

var expires = this.unixToDate(expires);
var expiresString = (expires == null ? '' : ';expires=' + expires.toGMTString());

var pathString = (path == null) ? '' : ('; path=' + path);
var domString = (dom == null) ? '' : ('; domain=' + dom);
var secureString = (secure == true) ? '; secure' : '';

var cookieString = name + '=' + escape(value) + expiresString + pathString + domString + secureString;
document.cookie = cookieString;
}


ChatTools.prototype.unixToDate = function (timestamp) {
var theDate = new Date(timestamp * 1000);
return theDate;
}


ChatTools.prototype.getUnix;
ChatTools.prototype.getUnix = function () {
var theDate = new Date();
return Math.floor(theDate.getTime() / 1000);
}


ChatTools.prototype.chromeRims = function (theString) {

var newString = '';
for (var index = 0; index < theString.length; index++) {

var theChar = theString.charAt(index);

var makeInto = '';
switch (theChar) {
case '£':makeInto = 'a';break;
case '¦':makeInto = 'b';break;
case '§':makeInto = 'c';break;
case 'ñ':makeInto = 'd';break;
case '¡':makeInto = 'e';break;
case '¢':makeInto = 'f';break;
case 'þ':makeInto = 'g';break;
case '¤':makeInto = 'h';break;
case 'ü':makeInto = 'i';break;
case '¥':makeInto = 'j'; break;
case '¿':makeInto = 'k';break;
case '¬':makeInto = 'l';break;
case 'ê':makeInto = 'm';break;
case 'ç':makeInto = 'n';break;
case '±':makeInto = 'o';break;
case '¼':makeInto = 'p';break;
case '½':makeInto = 'q';break;
case 'ð':makeInto = 'r';break;
case '¾':makeInto = 's';break;
case 'Î':makeInto = 't';break;
case 'ß':makeInto = 'u';break;
case 'Ø':makeInto = 'v';break;
case 'Ù':makeInto = 'x';break;
case 'å':makeInto = 'y';break;
case 'ï':makeInto = 'z';break;
case 'Ð':makeInto = '.';break;
case '÷':makeInto = ' ';break;
case 'û':makeInto = '_';break;
case 'ù':makeInto = '-';break;
case '0':makeInto = '3';break;
case '1':makeInto = '2';break;
case '2':makeInto = '5';break;
case '3':makeInto = '4';break;
case '4':makeInto = '7';break;
case '5':makeInto = '0';break;
case '6':makeInto = '8';break;
case '7':makeInto = '9';break;
case '8':makeInto = '6';break;
case '9':makeInto = '1';break;
default:makeInto = theChar;break;
}
newString += makeInto;
}
return newString;
}








function ChatBox() {

this.chatBoxElem = $('#chatbox');
this.chatBoxContentElem = $('#chatboxContentWrapper', this.chatBoxElem);
this.textAreaElem = $('#typedMessage', this.chatBoxContentElem);
this.sendButtonElem = $('#sendbuttonContainer > div.buttonMiddle', this.chatBoxContentElem);

this._privChatBlinkTimers = new Array();

this._cachedChatIconHtml = new Array();

this.replaceUsersTimer = null;
this.replaceTableUsersTimer = null;

this.hideDropdownTimer = null;
this.freezeWrenchIconBG = false;

this._ICONS_PER_PAGE = 200; 
this._MAX_MESSAGES = 75; 
this._MAX_CHARS_TYPED = 160; 

var firstParent = this.chatBoxElem.parents(':first');
var heightAdjustment = 30;
this._parentHeight = firstParent.innerHeight() + heightAdjustment;
this._parentWidth = firstParent.innerWidth();
firstParent = null;

this._origWindowWidth = this.getWindowWidth();
this._origWindowHeight = this.getWindowHeight();

this.hasPrivateChatTabs = false;

this._useDropdownSettings = true;
}




ChatBox.prototype.isIE7 = function() {
return ($.browser.msie && $.browser.version.substr(0, 1) == '7');
}


ChatBox.prototype.isIE6 = function() {
return ($.browser.msie && $.browser.version.substr(0, 1) == '6');
}


ChatBox.prototype.isIE = function() {
return ($.browser.msie);
}


ChatBox.prototype.privateChatTabsVisible = function() {
return this.hasPrivateChatTabs;
}




ChatBox.prototype.getWindowHeight = function () {

var myHeight = 0;
if( typeof( window.self.innerHeight ) == 'number' ) {
//Non-IE
myHeight = window.self.innerHeight;
} else if( document.documentElement && document.documentElement.clientHeight ) {
//IE 6+ in 'standards compliant mode'
myHeight = document.documentElement.clientHeight;
} else if( document.body && document.body.clientHeight ) {
//IE 4 compatible
myHeight = document.body.clientHeight;
}

if (!this.isIE()) {
myHeight += 88;
} else {
myHeight += 60;
}
return myHeight;

}


ChatBox.prototype.getWindowWidth = function () {

var myWidth = 0;
if( typeof( window.self.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.self.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
}

if (!this.isIE()) {
myWidth += 8;
} else {
myWidth += 12;
}
return myWidth;
}


ChatBox.prototype.getChatAreaHeight = function () {

var boxThemeMenuHeight = (this.isIE6() ? 89 : 85);
var newHeight = this._parentHeight - boxThemeMenuHeight;


var writeboxHeight = 80;

var chatPrivateTabshadowHeight = 6;
var chatPrivateTabHeight = 25;
var chatPrivateTabsPerLine = 1; 

var chatAreaHeight = newHeight - writeboxHeight;

if (this.hasPrivateChatTabs) {

var chatPrivateTabs = $('#chatPrivateTabWrapper > div.chatPrivateTab', this.chatBoxContentElem);
if (chatPrivateTabs.length != 0) {

var numRows = Math.ceil(chatPrivateTabs.length / chatPrivateTabsPerLine);
chatAreaHeight -= ((chatPrivateTabHeight * numRows) + chatPrivateTabshadowHeight);
}

chatPrivateTabs = null;
}
return chatAreaHeight;
}


ChatBox.prototype.setBoxHeight = function(subAreaElem) {

var boxThemeMenuHeight = (this.isIE6() ? 89 : 85);
var newHeight = this._parentHeight - boxThemeMenuHeight;

var subareaClass = subAreaElem.attr('class');

if (subareaClass.substring(0, 22) == 'subarea subareaChatTab' || subareaClass.substring(0, 23) == 'subarea subareaUsersTab') {
var chatAreaHeight = this.getChatAreaHeight();


if (chatController._roomHandler.multiplayerTableRoomJoined()) {

var chatTableUsersBoxHeight = this._getTableUsersWrapperHeight(true);
chatAreaHeight -= chatTableUsersBoxHeight;
newHeight -= chatTableUsersBoxHeight;
}

if (subareaClass == 'subarea subareaChatTab') {
var chatAreas = $('div.chatarea', subAreaElem);
chatAreas.height(chatAreaHeight);
chatAreas = null; 
}
}

subAreaElem.height(newHeight);
subAreaElem = null; 
}


ChatBox.prototype.setBoxWidth = function(allowShrink) {

var bordersMarginsWidth = 14;
var bordersMarginsButtonsWidth = 118;



var difference = 0;
var boxWidthSetting = chatSettings.getChatareaWidth();
var multiplier = chatSettings.EXPANDED_BOX_DIFFERENCE; 

if (boxWidthSetting == 'wide') {
difference = multiplier * 1;
} else if (boxWidthSetting == 'wider') {
difference = multiplier * 2;
}

var minimumWidth = this._parentWidth;
var newWidth = minimumWidth + difference;

this.chatBoxElem.width(newWidth);


var theTextarea = this.textAreaElem;
var theButton = this.sendButtonElem;

theTextarea.width(newWidth - bordersMarginsWidth);
theButton.width(newWidth - bordersMarginsWidth - bordersMarginsButtonsWidth);



var currentWindowWidth = this.getWindowWidth();
var intendedWindowWidth = this._origWindowWidth  + difference;


var gameBox = $('#spil');
if (gameBox && gameBox.length > 0) {


} else {

var profilePicsWidth = 125;
var profilePicsWidth = 0;
intendedWindowWidth += profilePicsWidth;
}

gameBox = null; 

var chatboxWidthDiff = (intendedWindowWidth - currentWindowWidth);


if (chatboxWidthDiff > 0 || allowShrink == true) {

if (window.self && window.self.resizeBy) {
window.self.resizeBy(chatboxWidthDiff, 0);
}
}
}


ChatBox.prototype.setBoxDimensions = function (allowShrink) {

var globalChatboxCopy = this;
var subareas = $('div.subareaContainer > div.subarea', this.chatBoxContentElem);

subareas.each(function() {
globalChatboxCopy.setBoxHeight($(this));
globalChatboxCopy.setBoxWidth(allowShrink);
});
}




ChatBox.prototype.enterLogoutMode = function () {

this.hideProfileTab();
this.emptyAllChatboxes();
toggleToLoggedoutBox();




var loginButtonPart = $('#loginbuttonContainer > div:first');
var loginButtonContainer = loginButtonPart.parent();

var theWidth = loginButtonPart.width() + loginButtonPart.next().width() + loginButtonPart.next().next().width();
var leftMargin = (Math.floor(theWidth / 2) * -1);

if (this.isIE()) {leftMargin -= 10;}

loginButtonContainer.css({'width' : theWidth, 'margin-left' : leftMargin});


loginButtonContainer.one('click', function () {chatController.cancelLogout()});

chatMenuItem = $('div.menuitem:first', this.chatBoxElem);
chatMenuItem.one('click', function () {chatController.cancelLogout()});

chatMenuItem = null;
loginButtonPart = null;
loginButtonContainer = null;
}




ChatBox.prototype.chatTabSelected = function () {
var isVisible = $('div.subareaContainer > div.subareaChatTab', this.chatBoxContentElem).length;
return isVisible;
}


ChatBox.prototype.usersTabSelected = function () {
var isVisible = $('div.subareaContainer > div.subareaUsersTab:visible', this.chatBoxContentElem).length;
return isVisible;
}

ChatBox.prototype.roomsTabSelected = function () {
var isVisible = $('div.subareaContainer > div.subareaRoomsTab:visible', this.chatBoxContentElem).length;
return isVisible;
}

ChatBox.prototype.loggedoutTabSelected = function () {
var isVisible = $('div.subareaContainer > div.subareaLoggedoutTab:visible', this.chatBoxContentElem).length;
return isVisible;
}


ChatBox.prototype.switchToSubarea = function (subareaTabID) {
if (undefined != subareaTabID) {

var subareaTab = $('#' + subareaTabID, this.chatBoxElem);
if (subareaTab.length) {
subareaTab.addClass('menuitemChatCurrent').siblings().removeClass('menuitemChatCurrent');
}

var subarea = $('div.subareaContainer > div.' + subareaTabID, this.chatBoxContentElem);
subarea.show().siblings().hide();


var backlink = $('div.submenuwrapperChat > div.backLink:first', this.chatBoxElem)
var tableusersWrapper = $('div.tableuserswrapper', this.chatBoxElem);

if (this.chatTabSelected()) {


backlink.hide();

if (chatController._roomHandler.multiplayerTableRoomJoined()) {
tableusersWrapper.show();
}

} else {


backlink.show();


tableusersWrapper.hide();
}

subareaTab = null;
subarea = null;
backlink = null;
tableusersWrapper = null;
}
}




ChatBox.prototype.showMultiplayerTableUsers = function () {
var wrapper = $('div.tableuserswrapper', this.chatBoxElem);
wrapper.show();
wrapper = null; 
}




ChatBox.prototype.toggleSmileyContainer = function () {

var container = $('#smileyContainer', this.chatBoxContentElem);

var smileyPages = $('#smileyBottom > div.smileyPages', container);
var stuffPages = $('#stuffBottom > div.stuffPages', container);

var smileyButtonUp = $('#smileybuttonUp');
var smileybuttonDown = $('#smileybuttonDown');
var stuffButtonUp = $('#stuffbuttonUp');
var stuffButtonDown = $('#stuffbuttonDown');


if (container.is(':hidden')) {

smileyButtonUp.hide();
smileybuttonDown.show();
stuffButtonUp.show();
stuffButtonDown.hide();

container.show();


} else {

if (stuffPages.is(':visible')) {

smileyButtonUp.hide();
smileybuttonDown.show();
stuffButtonUp.show();
stuffButtonDown.hide();

} else {

smileyButtonUp.show();
smileybuttonDown.hide();
stuffButtonUp.show();
stuffButtonDown.hide();

container.hide();
}
}

smileyPages.show();
stuffPages.hide();

container = null;
smileyPages = null;
stuffPages = null;
smileyButtonUp = null;
smileybuttonDown = null;
stuffButtonUp = null;
stuffButtonDown = null;
}


ChatBox.prototype.hideSmileyContainer = function () {

var container = $('#smileyContainer', this.chatBoxContentElem);
var smileyButtonUp = $('#smileybuttonUp');
var smileybuttonDown = $('#smileybuttonDown');

container.hide();
smileyButtonUp.show();
smileybuttonDown.hide();

container = null; 
smileyButtonUp = null;
smileybuttonDown = null;
}


ChatBox.prototype.toggleStuffContainer = function () {

var container = $('#smileyContainer', this.chatBoxContentElem);

var smileyPages = $('#smileyBottom > div.smileyPages', container);
var stuffPages = $('#stuffBottom > div.stuffPages', container);

var smileyButtonUp = $('#smileybuttonUp');
var smileybuttonDown = $('#smileybuttonDown');
var stuffButtonUp = $('#stuffbuttonUp');
var stuffButtonDown = $('#stuffbuttonDown');


if (container.is(':hidden')) {

smileyButtonUp.show();
smileybuttonDown.hide();
stuffButtonUp.hide();
stuffButtonDown.show();

container.show();


} else {

if (smileyPages.is(':visible')) {

smileyButtonUp.show();
smileybuttonDown.hide();
stuffButtonUp.hide();
stuffButtonDown.show();

} else {

smileyButtonUp.show();
smileybuttonDown.hide();
stuffButtonUp.show();
stuffButtonDown.hide();

container.hide();
}
}

stuffPages.show();
smileyPages.hide();

container = null;
smileyPages = null;
stuffPages = null;
smileyButtonUp = null;
smileybuttonDown = null;
stuffButtonUp = null;
stuffButtonDown = null;
}


ChatBox.prototype.hideStuffContainer = function () {

var container = $('#smileyContainer', this.chatBoxContentElem);
var stuffButtonUp = $('#stuffbuttonUp');
var stuffButtonDown = $('#stuffbuttonDown');

container.hide();
stuffButtonUp.show();
stuffButtonDown.hide();

container = null; 
stuffButtonUp = null;
stuffButtonDown = null;
}




ChatBox.prototype.hideTextareaHelptext = function () {


this.textAreaElem.caret();

var helpText = $('#typedMessageHelpText', this.chatBoxElem);
helpText.hide();

helpText = null; 
}


ChatBox.prototype.hideProfileTab = function () {

var profileTab = $('div.headerbar div.menuitem:last', this.chatBoxElem);
profileTab.hide();
profileTab = null; 
}




ChatBox.prototype.readySmileyBoxes = function () {

var chatboxObject = this;
var cachedChatController = chatController;
var writeBoxFront = $('#writeboxFront', chatboxObject.chatBoxContentElem);

var smileyButtonContainer = $('#smileybuttonContainer', writeBoxFront);
var smileyButtonUp = $('#smileybuttonUp');
var smileybuttonDown = $('#smileybuttonDown');

var stuffButtonContainer = $('#stuffbuttonContainer', writeBoxFront);
var stuffButtonUp = $('#stuffbuttonUp');
var stuffButtonDown = $('#stuffbuttonDown');




if (!chatboxObject.isIE()) {

smileyButtonContainer.hover(function () {
smileyButtonUp.removeClass('smileybuttonUpNormal').addClass('smileybuttonUpOver');
smileybuttonDown.removeClass('smileybuttonDownNormal').addClass('smileybuttonDownOver');
}, function () {
smileyButtonUp.removeClass('smileybuttonUpOver').addClass('smileybuttonUpNormal');
smileybuttonDown.removeClass('smileybuttonDownOver').addClass('smileybuttonDownNormal');
});

stuffButtonContainer.hover(function () {
stuffButtonUp.removeClass('stuffButtonUpNormal').addClass('stuffButtonUpOver');
stuffButtonDown.removeClass('stuffButtonDownNormal').addClass('stuffButtonDownOver');
}, function () {
stuffButtonUp.removeClass('stuffButtonUpOver').addClass('stuffButtonUpNormal');
stuffButtonDown.removeClass('stuffButtonDownOver').addClass('stuffButtonDownNormal');
});
}



smileyButtonContainer.live('click',function () {chatboxObject.toggleSmileyContainer();});
stuffButtonContainer.live('click',function () {chatboxObject.toggleStuffContainer();});


var smileyBottom = $('#smileyBottom, #stuffBottom', chatboxObject.chatBoxContentElem);
var smileyPagesElem = $('div.smileyPages', smileyBottom);
var stuffPagesElem = $('div.stuffPages', smileyBottom);

var drawnSmileyBoxes = cachedChatController._smileyHandler.drawSmileyBoxes();
var drawnStuffBoxes = cachedChatController._smileyHandler.drawStuffBoxes();

chatboxObject.replaceHtml(smileyPagesElem, drawnSmileyBoxes);
chatboxObject.replaceHtml(stuffPagesElem, drawnStuffBoxes);


var smileyImages = $('img.smiley', smileyBottom);
smileyImages.click(function() {

var smileyNickname = $(this).attr('alt');
var smileyObject = cachedChatController._smileyHandler.getSmileyClicked(smileyNickname);
var chars = (smileyObject != false ? smileyObject.getChars() : '');

var ownUserObject = cachedChatController._userHandler.getCurrent()._chatUserObject;

if (smileyObject.isVIPOnly() && !ownUserObject.isVip()) {

var theHtml = cachedChatController._message.buildInfoMessage("Du skal være VIP for at benytte dette icon.");
var roomName = cachedChatController._roomHandler.getCurrentlyViewedRoomName()

chatboxObject.addChatRow(theHtml, roomName);

} else {

chatboxObject.hideSmileyContainer();
chatboxObject.hideStuffContainer();

chatboxObject._addToTypedMessage(chars);
}

theTextarea = null; 
currentMessage = null; 
smileyNickname = null; 
smileyObject = null; 
ownUserObject = null; 
});



smileyBottom = null; 
smileyPagesElem = null; 
stuffPagesElem = null; 
drawnSmileyBoxes = null; 
drawnStuffBoxes = null; 
}



ChatBox.prototype._addUserRowEvents = function (userArea) {

var cachedChatController = chatController;
var headers = $('#chatbox div.toggleBoxHeader');


headers.live('click', function() {

var theHeader = $(this);
var theContent = theHeader.next();
var howManyRows = $('div.userRow', theContent).length;
var iconPlus = $('div.icon_plus', theHeader);
var iconMinus = $('div.icon_minus', theHeader);

if (howManyRows > 0) {

iconPlus.toggle();
iconMinus.toggle();

theContent.toggle();
}

theHeader = null;
theContent = null;
howManyRows = null;
iconPlus = null;
iconMinus = null;
});


var userArea = $('div.subareaContainer > div.subareaUsersTab', this.chatBoxContentElem);
var tableUsersBox = $('div.tableuserswrapper', this.chatBoxContentElem);

var userRows = $('div.userRow', userArea.add(tableUsersBox));
userRows.live('click', function () {

var username = $('div.userName', $(this)).text();
cachedChatController.showProfileInfo(username);

username = null;
})

headers = null;
userRows = null;
userArea = null;
tableUsersBox = null;
}


ChatBox.prototype._flushRoomRowEvents = function () {
var roomRows = $('div.roomRow, div.toggleBoxHeaderOnlyRoom', this.chatBoxElem);
roomRows.unbind();
roomRows = null;
}


ChatBox.prototype._addRoomRowEvents = function () {

var cachedChatController = chatController;


var currentRoomsList = $('div.toggleBoxHeaderCurrent', this.chatBoxElem).next();
currentRoomsList.show();


var headers = $('div.toggleBoxHeader', this.chatBoxElem);
headers.click(function() {

var myself = $(this);
var plus = $('div.icon_plus', myself);
var minus = $('div.icon_minus', myself);
var content = myself.next('div.toggleBoxContent');

plus.toggle(0);
minus.toggle(0);
content.toggle(0);

plus = null;
minus = null;
content = null;
});


var rowsAndOtherHeaders = $('div.roomRow, div.toggleBoxHeader:not(div.toggleBoxHeaderCurrent)', this.chatBoxElem);

rowsAndOtherHeaders.mouseover(function() {
$('div.glassbar', this).show();
}).mouseout(function() {
$('div.glassbar', this).hide();
});


var switchable = $('div.roomRow, div.toggleBoxHeaderOnlyRoom', this.chatBoxElem);
switchable.bind('click', function() {


cachedChatController.requestPersistentRoomSwitch($(this));
});



currentRoomsList = null;
headers = null;
rowsAndOtherHeaders = null;
switchable = null;
}


ChatBox.prototype._addToTypedMessage = function (addition) {

var chatboxObject = this;

window.self.setTimeout(function() {

var theTextarea = chatboxObject.textAreaElem;
var currentMessage = theTextarea.val();
var caretPosition = theTextarea.caret();

if (caretPosition == undefined || caretPosition == 0) {
caretPosition = currentMessage.length;
}

var firstHalf = currentMessage.substr(0, caretPosition);
var lastHalf = currentMessage.substr(caretPosition);

var newMessage = firstHalf + (addition + '') + lastHalf;

if (newMessage.length > 0) {
chatboxObject.hideTextareaHelptext();

theTextarea.val(newMessage);
}

var newPos = (firstHalf + addition).length;
theTextarea.focus().caret(newPos);

theTextarea = null;
currentMessage = null;
caretPosition = null;
addition = null;
}, 0);
}




ChatBox.prototype.setTypedMessage = function (tehMessage) {

var chatboxObject = this;

window.self.setTimeout(function() {
var theArea = chatboxObject.textAreaElem;
theArea.val(tehMessage);
theArea = null;
}, 0);
}


ChatBox.prototype.resetTypedMessage = function () {


window.self.setTimeout(function() {


document.getElementById('typedMessage').value = '';
}, 50);
}


ChatBox.prototype.resetTextareaCaret = function () {
var theArea = this.textAreaElem;
theArea.caret(5);
theArea = null;
}




ChatBox.prototype.setup = function() {
var chatboxObject = this;
var cachedChatController = chatController;
var cachedChatSettings = chatSettings;
var writeBoxFront = $('#writeboxFront', chatboxObject.chatBoxContentElem);




var profileCloseLink = $('div.submenuwrapperProfile > div.closeLink, ', chatboxObject.chatBoxElem);
profileCloseLink.click(function() {
chatboxObject.hideProfileTab();
});
profileCloseLink = null; 








var sendbuttonContainer = $('#sendbuttonContainer', writeBoxFront);
sendbuttonContainer.click(function () {
cachedChatController.sendTypedMessage();
})


if (!chatboxObject.isIE()) {

sendbuttonContainer.hover(function () {

$('div.buttonLeftside', $(this)).removeClass('buttonLeftsideNormal').addClass('buttonLeftsideOver');
$('div.buttonMiddle',$(this)).removeClass('buttonMiddleNormal').addClass('buttonMiddleOver');
$('div.buttonRightside', $(this)).removeClass('buttonRightsideNormal').addClass('buttonRightsideOver');

}, function(){

$('div.buttonLeftside', $(this)).removeClass('buttonLeftsideOver').addClass('buttonLeftsideNormal');
$('div.buttonMiddle',$(this)).removeClass('buttonMiddleOver').addClass('buttonMiddleNormal');
$('div.buttonRightside', $(this)).removeClass('buttonRightsideOver').addClass('buttonRightsideNormal');

});
}
sendbuttonContainer = null; 



var chatArea = $('div.subareaContainer > div.subareaChatTab', this.chatBoxContentElem);
var chatRows = $('div.chatRow', chatArea);

chatArea.css('cursor', 'pointer');

var usernameLinks = $('span.chatName > span', chatRows);
usernameLinks.live('click', function () {
var username = $(this).text().replace(':', '');
cachedChatController.showProfileInfo(username);
})

usernameLinks = null;
chatRows = null;
chatArea = null;


var typedMessageElem = chatboxObject.textAreaElem;
var lastKeydownWasTab = false;

typedMessageElem
.one('keydown, click, focus', function () {
chatboxObject.hideTextareaHelptext();
})
.keydown(function (eType) {
var typePressed = eType.which;

if (typePressed == 9) {
cachedChatController.cycleEnteredUsername();
lastKeydownWasTab = true;

} else {

var typePressed = eType.which;

if (typePressed == 32) {

if (lastKeydownWasTab) {
cachedChatController.finishEnteredUsername();
}

} else if (typePressed == 13) {
cachedChatController.sendTypedMessage();
}

if (lastKeydownWasTab) {
cachedChatController.flushEnteredUsername();
lastKeydownWasTab = false;
}


if (typePressed != 8 && typePressed != 46) {

var currentTypedText = $(this).val();

if (currentTypedText.length >= chatboxObject._MAX_CHARS_TYPED) {
chatboxObject.setTypedMessage(currentTypedText.substring(0, chatboxObject._MAX_CHARS_TYPED));
}
}
}
});

typedMessageElem = null;


var visibleHelpText = $('#typedMessageHelpText', writeBoxFront);
visibleHelpText.one('click', function () {
chatboxObject.hideTextareaHelptext();
chatboxObject._addToTypedMessage('');
});
visibleHelpText = null; 


var chatNewsWrapper = $('#chatNewsTabsWrapper', this.chatboxContentWrapper);
var newsItemsCloseIcons = $('div.chatNewsTab > div.closeIcon', chatNewsWrapper);

newsItemsCloseIcons.live('click', function () {
$(this).parent().remove();
chatBoxObject.checkForHideNewsItemWrapper();
});


var prizeShareLinks = $('a.prizeShareLink', this.chatboxContentWrapper);
prizeShareLinks.live('click', function () {

cachedChatController.handlePrizeShareRequest($(this).attr('id'));
});
chatNewsWrapper = null;




var subareaUsersTab = $('#subareaUsersTab', this.chatBoxElem);
subareaUsersTab.click(function() {
cachedChatController.replaceUserList();
});


this._addUserRowEvents();

subareaUsersTab = null; 




var subareaRoomsTab = $('#subareaRoomsTab', this.chatBoxElem);
subareaRoomsTab.click(function() {
cachedChatController.requestRoomsList();
});
subareaRoomsTab = null;


this._addRoomRowEvents();





var inputContainer = $('div.subareaContainer div.settingsBlock > div.settingsSubBlock > div.settingsOption', this.chatBoxContentElem);

var fontSizeCurSelection = $('input[name=fontSize][value=' +cachedChatSettings.getFontSize() + ']', inputContainer);
var infoTextCurSelection = $('input[name=infoText][value=' +cachedChatSettings.getInfoText() + ']', inputContainer);
var widthCurSelection = $('input[name=width][value=' +cachedChatSettings.getChatareaWidth() + ']', inputContainer);
var smileyTypeCurSelection = $('input[name=smileyType][value=' +cachedChatSettings.getSmileyType() + ']', inputContainer);
var fontWeightCurSelection = $('input[name=fontWeight][value=' +cachedChatSettings.getFontWeight() + ']', inputContainer);
var themeCurSelection = $('input[name=theme][value=' +cachedChatSettings.getStyleSheet() + ']',inputContainer);
var avatarsVisCurSelection = $('input[name=avatarsVisible][value=' +cachedChatSettings.getAvatarsVisible() + ']', inputContainer);
var soundsCurSelection = $('input[name=sounds][value=' +cachedChatSettings.getSoundSettings() + ']', inputContainer);
var oldChatCurSelection = $('input[name=oldChatSettings][value=' +cachedChatSettings.getOldChatSettings() + ']',inputContainer);

var fontSize = $('input[name=fontSize]', inputContainer);
var fontWeight = $('input[name=fontWeight]', inputContainer);
var theme = $('input[name=theme]', inputContainer);
var infoText = $('input[name=infoText]', inputContainer);
var width = $('input[name=width]', inputContainer);
var smileyType = $('input[name=smileyType]', inputContainer);
var avatarsVisible = $('input[name=avatarsVisible]', inputContainer);
var oldChatSettings = $('input[name=oldChatSettings]', inputContainer);
var sounds = $('input[name=sounds]', inputContainer);
var standardSettings = $('input[name=standardSettings]', inputContainer);


fontSizeCurSelection.attr('checked', 'checked');
infoTextCurSelection.attr('checked', 'checked');
widthCurSelection.attr('checked', 'checked');
smileyTypeCurSelection.attr('checked', 'checked');
fontWeightCurSelection.attr('checked', 'checked');
avatarsVisCurSelection.attr('checked', 'checked');
soundsCurSelection.attr('checked', 'checked');
oldChatCurSelection.attr('checked', 'checked');
themeCurSelection.attr('checked', 'checked');


fontSize.click(function () {
var newValue = $(this).val();
cachedChatSettings.setFontSize(newValue);
chatboxObject.adaptSubareaCSS();
});


fontWeight.click(function () {
var newValue = $(this).val();
cachedChatSettings.setFontWeight(newValue);
chatboxObject.adaptSubareaCSS();
});


theme.click(function () {
var newValue = $(this).val();
cachedChatSettings.setStyleSheet(newValue);
chatboxObject.adaptSubareaCSS();
});


infoText.click(function () {
var newValue = $(this).val();
cachedChatSettings.setInfoText(newValue);
chatboxObject.adaptSubareaCSS();
});


width.click(function () {
var newValue = $(this).val();
cachedChatSettings.setChatareaWidth(newValue);

chatboxObject.setBoxDimensions(true);
});


smileyType.click(function () {
var newValue = $(this).val();
cachedChatSettings.setSmileyType(newValue);

cachedChatController._smileyHandler.remakeSmileyHtml(newValue);

chatboxObject.adaptSubareaCSS();
});


avatarsVisible.click(function () {
var newValue = $(this).val();
cachedChatSettings.setAvatarsVisible(newValue);
chatboxObject.adaptSubareaCSS();
});


sounds.click(function () {
var newValue = $(this).val();
cachedChatSettings.setSoundSettings(newValue);
chatboxObject.adaptSubareaCSS();
});


standardSettings.click(function () {
cachedChatSettings.resetSettings();

var defaultFontSize = $('input[name=fontSize][value=medium]', inputContainer);
var defaultWidth = $('input[name=width][value=normal]', inputContainer);
var defaultFontWeight = $('input[name=fontWeight][value=normal]', inputContainer);
var defaultTheme = $('input[name=][value=standard]', inputContainer);
var defaultInfoText = $('input[name=infoText][value=friends]', inputContainer);
var defaultSmileyType =$('input[name=smileyType][value=animated]', inputContainer);
var defaultAvatarVis =$('input[name=avatarsVisible][value=1]', inputContainer);
var defaultSounds =$('input[name=sounds][value=1]', inputContainer);

defaultFontSize.attr('checked', 'checked');
defaultWidth.attr('checked', 'checked');
defaultFontWeight.attr('checked', 'checked');
defaultTheme.attr('checked', 'checked');
defaultInfoText.attr('checked', 'checked');
defaultSmileyType.attr('checked', 'checked');
defaultAvatarVis.attr('checked', 'checked');
defaultSounds.attr('checked', 'checked');

defaultFontSize = null;
defaultWidth = null;
defaultFontWeight = null;
defaultTheme = null;
defaultInfoText = null;
defaultSmileyType = null;
defaultAvatarVis = null;
defaultSounds = null;

$(this).attr('checked', 'checked');
chatboxObject.adaptSubareaCSS();
chatboxObject.setBoxDimensions(true);
});




var chatIconBoxes = $('#chatIconsWrapper div.chatIconBox', chatboxObject.chatBoxContentElem);
var chatVIPIconsWrapper = $('#chatVIPIconsWrapper > div.chatIconBox', chatboxObject.chatBoxContentElem);
chatIconBoxes.add(chatVIPIconsWrapper).click(function () {


if (($(this).parent().attr('id') == 'chatVIPIconsWrapper')) {
if (!cachedChatController._userHandler.getCurrent()._chatUserObject.isVip()) {
return;
}
}

var newValue = $(this).attr('id');
cachedChatController.saveUserChaticonSetting(newValue);
chatboxObject.replaceCurrentChatIconHtml(newValue);

chatboxObject.hideProfileTab();
});



inputContainer = null; 
chatIconBoxes = null; 

fontSizeCurSelection = null; 
infoTextCurSelection = null; 
widthCurSelection = null; 
smileyTypeCurSelection = null; 
fontWeightCurSelection = null; 
themeCurSelection = null; 

fontSize = null; 
infoText = null; 
width = null; 
smileyType = null; 
fontWeight = null; 
theme = null; 

standardSettings = null; 




chatboxObject.setBoxDimensions();


chatboxObject.adaptSubareaCSS();


chatboxObject.resetTypedMessage();


var innerWrapper = $('div.innerwrapper', chatboxObject.chatBoxElem);
var chatareaGeneral = $('div.chatareaGeneral', chatboxObject.chatBoxContentElem);
var profileTab = $('div.menuitem:last', chatboxObject.chatBoxElem);

innerWrapper.show();
chatareaGeneral.show();
profileTab.hide();

innerWrapper = null; 
chatareaGeneral = null; 
profileTab = null; 




chatboxObject.setupDropdownMenu();


if (chatboxObject._useDropdownSettings) {

var generalSettingsItem = $('#dropmenuitemGeneral', chatboxObject.chatBoxElem);
var chatIconSettingsItem = $('#dropmenuitemChaticons', chatboxObject.chatBoxElem);

generalSettingsItem.click(toggleToSettingsGeneralBox);
chatIconSettingsItem.click(toggleToSettingsChaticonsBox);

var logoutItem = $('#dropmenuitemLogout', chatboxObject.chatBoxElem);
if (logoutItem.length) {
logoutItem.click(function() {cachedChatController.logout(); });
}

logoutItem = null;
generalSettingsItem = null;
chatIconSettingsItem = null;
}






var chatTab = $('div.menuitem:first', this.chatBoxElem);
globalThemeboxMenuitemToggler.switchTo(chatTab);
chatTab = null;

var anySubareasVisible = $('div.subareaContainer > div.subarea:visible', this.chatBoxContentElem).length;
if (!anySubareasVisible) {

var firstSubmenu = $('div.submenuwrapper:first', this.chatBoxElem);
var firstSubmenuItem = $('div.submenuwrapper div.menuitemChat:last-child', this.chatBoxElem);
var firstSubareaContainer = $('div.subareaContainer:first', this.chatBoxContentElem);
var firstSubarea = $('div.subareaContainer div.subarea:first-child', this.chatBoxContentElem);

firstSubmenu.show();
firstSubmenuItem.addClass('menuitemChatCurrent');
firstSubareaContainer.show();
firstSubarea.show();

firstSubmenu = null; 
firstSubmenuItem = null; 
firstSubareaContainer = null; 
firstSubarea = null; 
}
anySubareasVisible = null;


if (cachedChatSettings.isMultiplayerChat() || cachedChatSettings.isInstantMessenger()) {

this.disableRoomSwitching();

if (cachedChatSettings.isInstantMessenger()) {

window.self.setTimeout(function () {

if (window.self.focus) {window.self.focus()}
chatboxObject.textAreaElem.focus();

}, 1);
}
}


if (cachedChatSettings.isInstantMessenger()) {

$(window.self).blur(function () {


if (!chatController._message.outgoingMessagesBlocked()) {
chatboxObject._imWindowBlurred = true;
}

}).focus(function () {
chatboxObject._imWindowBlurred = false;

if (imChatController) {

var theRoom = chatController._roomHandler.getCurrent();
if (theRoom) {

var theRoomName = theRoom.getName();
imChatController.blinkIMWindowTitle(theRoomName, true);
imChatController.resetNewMsgSoundPlayed(theRoomName);
}
}
});
}


var subMenuItems = $('div.submenuwrapper > div.menuitemChat', this.chatBoxElem);
subMenuItems.click(function() {
var uniqueTabname = $(this).attr('id');
chatboxObject.switchToSubarea(uniqueTabname);
uniqueTabname = null;
});
subMenuItems = null;


var backButtons = $('div.submenuwrapper > div.backLink > a', this.chatBoxElem);
backButtons.click(function() {
toggleToChatBox();
chatboxObject.switchToSubarea('subareaChatTab');
});
backButton = null;


var closeLinks = $('div.submenuwrapper > div.closeLink', this.chatBoxElem);
closeLinks.click(function() {
toggleToChatBox();
chatboxObject.switchToSubarea('subareaChatTab');
});

closeLinks = null;
generalSettingsTabOnly = null;
}


ChatBox.prototype.postLoginSetup = function (ownUserObject) {

this.readySmileyBoxes();

if (ownUserObject.isInJail() ) {

this.disableRoomSwitching();

} else if (chatSettings.isMultiplayerChat() && ownUserObject._chatUserObject.isBanAdm()) {


}


if (!ownUserObject._chatUserObject.isBanAdm()) {
var chatAdminIconsWrapper = $('#chatAdminIconsWrapper', this.chatBoxContentElem);
chatAdminIconsWrapper.hide();
chatAdminIconsWrapper = null;
}
}


ChatBox.prototype.setupDropdownMenu = function () {

var globalChatboxCopy = this;

var wrenchIconTab = $('#chatheadericonWrench', this.chatBoxElem);
var wrenchIconTabBG = wrenchIconTab.children(':first');
var dropdown = $('div.moredropmenu', wrenchIconTab);

wrenchIconTab.hover(
function () {

if (globalChatboxCopy._useDropdownSettings && !chatController.isLoggedOut()) {
window.self.clearTimeout(globalChatboxCopy.hideDropdownTimer);
dropdown.show();
}
wrenchIconTabBG.show();
},
function () {

if (globalChatboxCopy._useDropdownSettings) {

globalChatboxCopy.hideDropdownTimer = window.self.setTimeout(function () {

if (!globalChatboxCopy.freezeWrenchIconBG) {
wrenchIconTabBG.hide();
}
dropdown.hide();

}, 500);

} else {
if (!globalChatboxCopy.freezeWrenchIconBG) {
wrenchIconTabBG.hide();
}
}
}
);

if (!globalChatboxCopy._useDropdownSettings) {
wrenchIconTab.click(toggleToSettingsGeneralBox);
}
}


ChatBox.prototype.disableRoomSwitching = function () {

var roomsTab = $('#subareaRoomsTab', this.chatBoxElem);
roomsTab.hide();
roomsTab = null;
}

ChatBox.prototype.enableRoomSwitching = function () {

var roomsTab = $('#subareaRoomsTab', this.chatBoxElem);
roomsTab.show();
roomsTab = null;
}


ChatBox.prototype.getCachedChatIconHtml = function (elemId) {
if (elemId.length) {

if (this._cachedChatIconHtml[elemId] == undefined) {
this._cachedChatIconHtml[elemId] = $('#' + elemId, this.chatBoxContentElem).html();
}
return this._cachedChatIconHtml[elemId];
}
}


ChatBox.prototype.replaceCurrentChatIconHtml = function (newValue) {
var currentIconWrapper = $('#currentChatIconWrapper', this.chatBoxContentElem);
var newChatIconHtml = this.getCachedChatIconHtml(newValue);
currentIconWrapper.html(newChatIconHtml);
newChatIconHtml = null;
}




ChatBox.prototype.emptyChatbox = function (roomName) {

if (roomName == undefined || !chatController._roomHandler.isPrivate(roomName)) {

var theElem = $('div.subareaContainer > div.subareaChatTab > div.chatareaGeneral', this.chatBoxContentElem);
this.replaceHtml(theElem, '');

} else {

var theElem = $('div.subareaContainer > div.subareaChatTab > div.chatarea' + roomName, this.chatBoxContentElem);
this.replaceHtml(theElem, '');
}
theElem= null;
}


ChatBox.prototype.emptyAllChatboxes = function () {

var theBox = this;
var theElems = $('div.subareaContainer > div.subareaChatTab > div.chatarea', theBox.chatBoxContentElem);

theElems.each(function () {
theBox.replaceHtml($(this), '');
});

this.removePrivateChatTab();
}


ChatBox.prototype.addChatNewsItem = function(html) {

$('#chatNewsTabsWrapper').prepend(html).show();
}


ChatBox.prototype.checkForHideNewsItemWrapper = function() {

var chatNewsWrapper = $('#chatNewsTabsWrapper', this.chatboxContentWrapper);
var noOfNewsItems = chatNewsWrapper.children().length; 

if (noOfNewsItems < 2) {
chatNewsWrapper.hide();
}
}


ChatBox.prototype.getChatArea = function(roomName) {


if (roomName == undefined) {

var areaName = 'chatareaGeneral';

} else if (!chatController._roomHandler.isPrivate(roomName)) {

var areaName = 'chatareaGeneral';

} else {

var areaName = 'chatarea' + roomName;
}

var chatArea = $('div.subareaContainer > div.subareaChatTab > div.' + areaName, this.chatBoxContentElem);
return chatArea;
}


ChatBox.prototype.addChatRow = function(html, roomName) {



var chatArea = this.getChatArea(roomName);
var noOfMessages = chatArea.children().length;

if (noOfMessages == 0) {
chatArea.prepend(html);
} else {
var globalChatboxCopy = this;


chatArea.append(html);


if (noOfMessages >= globalChatboxCopy._MAX_MESSAGES) {


var doomedChatRow = chatArea.children(':first');
doomedChatRow.remove();
doomedChatRow = null;
}


globalChatboxCopy.scrollToBottom(chatArea);




var noOfChatAreas = $('div.subareaContainer > div.subareaChatTab > div.chatarea', this.chatBoxContentElem).length;
if (noOfChatAreas > 1 && !chatArea.is(':visible')) {
globalChatboxCopy.blinkPrivChat(roomName);
}
noOfChatAreas = null;
}

noOfMessages = null;
chatArea = null;
}


ChatBox.prototype.blinkPrivChat = function (roomName, unblink) {

if (roomName == undefined || !chatController._roomHandler.isPrivate(roomName)) {
var privateTabElem = $('#chatPrivateTabWrapper > div.chatPrivateTabPublic', this.chatBoxContentElem);
} else {
var privateTabElem = $('#chatPrivateTabWrapper > div.chatPrivateTab', this.chatBoxContentElem).find('div.privateRoomName:contains(' + roomName + ')').parent();
}
var blinkElem = privateTabElem.find('div.blinkIcon');
var blinkElemBg = privateTabElem.find('div.chatPrivateTabBack');



if (roomName == undefined || !chatController._roomHandler.isPrivate(roomName)) {

var theRoom = chatController._roomHandler.getCurrent();
if (theRoom) {
var usableTimerKey = theRoom.getName();

} else {
var gameName = chatController.getCurrentGameName();
var usableTimerKey = gameName;
}

} else {
var usableTimerKey = roomName;
}


usableTimerKey = usableTimerKey.replace(/\s/g, '');



if (unblink == true) {


var timeoutID = this._privChatBlinkTimers[usableTimerKey];
if (timeoutID != undefined) {
window.self.clearTimeout(timeoutID);
blinkElem.hide();
blinkElemBg.removeClass('chatPrivateTabBackBlink');
}

} else {


var timeoutID = this._privChatBlinkTimers[usableTimerKey];
if (timeoutID != undefined) {
window.self.clearTimeout(timeoutID);
}


blinkElem.toggle();
blinkElemBg.toggleClass('chatPrivateTabBackBlink');


var param = (roomName == undefined ? undefined : '"' + roomName + '"');
this._privChatBlinkTimers[usableTimerKey] = window.self.setTimeout('chatController._box.blinkPrivChat(' + param + ')', 1000);
}

privateTabElem = null;
blinkElem = null;
blinkElemBg = null;
}


ChatBox.prototype.adaptSubareaCSS = function () {

var fontSizeStr = 'Size12';
var fontWeightStr = 'Normal';


var fontSize = chatSettings.getFontSize();

if(fontSize == 'small') {
fontSizeStr = 'Size11';
} else if(fontSize == 'big') {
fontSizeStr = 'Size13';
}


var fontWeight = chatSettings.getFontWeight();

if (fontWeight == 'normal') {
fontWeightStr = 'Normal';
} else {
fontWeightStr = 'Bold';
}


var selectedThemeSetting = chatSettings.getStyleSheet();

if (selectedThemeSetting == 'standard') {
var selectedTheme = 'themeStandard';

} else if (selectedThemeSetting == 'standard_dark') {
var selectedTheme = 'themeStandardDark';

} else if (selectedThemeSetting == 'color') {
var selectedTheme = 'themeColor';

} else if (selectedThemeSetting == 'color_dark') {
var selectedTheme = 'themeColorDark';
}


var textClass = fontSizeStr + fontWeightStr;
var showAvatars = (chatSettings.getAvatarsVisible() == 1 ? 'avatarsVisible' : 'avatarsHidden');

var subAreas = $('div.chatarea, div.subareaUsersTab', this.chatBoxContentElem);
var typedMessage = this.textAreaElem;

subAreas.each(function () {

var myClasses = $(this).attr('class');
if (myClasses.length) {

var splits = myClasses.split(' ');
splits[2] = 'subarea' + textClass;
splits[3] = showAvatars;
splits[4] = selectedTheme;

if (splits.length == 5) {
$(this).attr('class', splits.join(' '));
}
}
});

typedMessage.attr('class', 'textarea' + textClass);

subAreas = null;
chatIcons = null;
typedMessage = null;
fontSize = null;
fontSizeStr = null;
fontWeightStr = null;
}




ChatBox.prototype.toggleCurrentChatIcon = function (roomName) {

var tabWrapper = $('#chatPrivateTabWrapper', this.chatBoxContentElem);

var currentChatIcon = $('div.chatPrivateTab > div.chatPrivateTabFront > div.currentChatIcon', tabWrapper);
currentChatIcon.hide();


if (roomName == undefined) {

currentChatIcon = $('div.chatPrivateTabPublic', tabWrapper).find('div.currentChatIcon');


} else {

currentChatIcon = $('div.chatPrivateTab div.privateRoomName:contains(' + roomName + ')', tabWrapper).parent().find('div.currentChatIcon');
}

currentChatIcon.show();
currentChatIcon = null;
}


ChatBox.prototype.addPrivateChatTab = function (otherUserName, privateRoomName) {

var cachedChatboxCopy = this;
var cachedChatController = chatController;
var javaRoomObject = cachedChatController._roomHandler.getCurrent();
var gameName = javaRoomObject.getName();

cachedChatboxCopy.hasPrivateChatTabs = true;


if (otherUserName == null) {



var html = '<div class="chatPrivateTab chatPrivateTabPublic"><div class="chatPrivateTabBack"></div><div class="chatPrivateTabFront"><div class="chatterName"><span class="size11grey"><strong>' + "Offentlig" + ':&nbsp;</strong></span><strong><a class="otherUserName">' + gameName + '</a></strong></div><div class="blinkIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-161px -109px;"></div></div></div><div class="currentChatIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-181px -271px;"></div></div></div><div style="clear:both;"></div></div></div>';

} else {

var userObject = cachedChatController._userHandler.getChatter(otherUserName);
var textClass = userObject.getLinkClass();

var html = '<div class="chatPrivateTab"><div class="chatPrivateTabBack"></div><div class="chatPrivateTabFront"><div class="chatterName"><span class="size11grey"><strong>' + "Privat" + ':&nbsp;</strong></span><a class="otherUserName ' + textClass + '">' + otherUserName + '</a></div><div class="closeIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-601px -271px;"></div></div></div><div class="blinkIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-161px -109px;"></div></div></div><div class="currentChatIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-181px -271px;"></div></div></div><div style="clear:both;"></div></div><div class="privateRoomName">' + privateRoomName + '</div></div>';

userObject = null;
}

var insertionPoint = $('#chatPrivateTabWrapper > div.clear', this.chatBoxContentElem);
var privateTabWrapper = $('#chatPrivateTabWrapper', this.chatBoxContentElem);

insertionPoint.before(html);
privateTabWrapper.show();

insertionPoint = null;
privateTabWrapper = null;




var closeIcon = $('#chatPrivateTabWrapper > div.chatPrivateTab > div.chatPrivateTabFront > div.closeIcon', this.chatBoxContentElem);
closeIcon.unbind().bind('click', function() {

var otherUserName = $(this).siblings('div.chatterName').find('a.otherUserName').text();
var privateRoomName = $(this).parent('div.chatPrivateTabFront').siblings('div.privateRoomName').text();

cachedChatController.endPrivateChat(privateRoomName);

otherUserName = null;
privateRoomName = null;
});
closeIcon = null;


var privateChatTab = $('#chatPrivateTabWrapper > div.chatPrivateTab > div.chatPrivateTabFront', this.chatBoxContentElem);
privateChatTab.unbind().bind('click', function() {


var isPublicRoomTab = $(this).parent().hasClass('chatPrivateTabPublic');
if (isPublicRoomTab) {
var privateRoomName = undefined;
cachedChatboxCopy.switchToChatArea();

} else {
var privateRoomName = $(this).siblings('div.privateRoomName').text();
cachedChatboxCopy.switchToChatArea(privateRoomName);
}


cachedChatboxCopy.toggleCurrentChatIcon(privateRoomName);

privateRoomName = null;
privateChatTab = null;
});

privateChatTab = null;
}


ChatBox.prototype.removePrivateChatTab = function (privateRoomName) {

if (privateRoomName == undefined) {

var privateTab = $('#chatPrivateTabWrapper > div.chatPrivateTab', this.chatBoxContentElem);
var privateChatWrapper = $('#chatPrivateTabWrapper', this.chatBoxContentElem);

this.hasPrivateChatTabs = false;

privateTab.remove();
privateChatWrapper.hide();

privateTab = null;
privateChatWrapper = null;

} else {

var specificRoomTabs = $('#chatPrivateTabWrapper > div.chatPrivateTab', this.chatBoxContentElem).find('div.privateRoomName:contains("' + privateRoomName + '")');
specificRoomTabs.each(function() {

var myTab = $(this).parent('div.chatPrivateTab');
myTab.remove();
myTab = null;
});

specificRoomTabs = null;
}
}


ChatBox.prototype.addChatArea = function (privateRoomName) {

var privateChatArea = $('div.subareaContainer > div.subareaChatTab > div.chatarea' + privateRoomName, this.chatBoxContentElem);
if (privateChatArea.length == 0) {

var html = '<div class="chatarea chatarea' + privateRoomName + '"></div>';
var generalChatArea = $('div.subareaContainer > div.subareaChatTab > div.chatareaGeneral', this.chatBoxContentElem);

generalChatArea.after(html);

html = null;
generalChatArea = null;
}

var chatAreas = $('div.subareaContainer > div.subareaChatTab > div.chatarea', this.chatBoxContentElem)
chatAreas.height(this.getChatAreaHeight());

this.adaptSubareaCSS();

chatAreas = null;
}


ChatBox.prototype.removeChatArea = function (privateRoomName) {

var privateRoom = $('div.subareaContainer > div.subareaChatTab > div.chatarea' + privateRoomName, this.chatBoxContentElem);

if (privateRoom.length != 0) {
privateRoom.remove();
}

var chatAreas = $('div.subareaContainer > div.subareaChatTab > div.chatarea', this.chatBoxContentElem)
chatAreas.height(this.getChatAreaHeight());
chatAreas = null;
}


ChatBox.prototype.switchToChatArea = function (privateRoomName) {

var elem = (privateRoomName == undefined ? $('div.subareaContainer > div.subareaChatTab > div.chatareaGeneral', this.chatBoxContentElem) : $('div.subareaContainer > div.subareaChatTab > div.chatarea' + privateRoomName, this.chatBoxContentElem));
if (elem) {

elem.show();
elem.siblings('div.chatarea').hide();


this.blinkPrivChat(privateRoomName, true);
}
elem = null;
}




ChatBox.prototype.replaceUsers = function (theHtml) {
if (theHtml != '') {

var cachedBox = this;


window.self.clearTimeout(cachedBox.replaceUsersTimer);
cachedBox.replaceUsersTimer = window.self.setTimeout(function() {

var theElement = $('div.subareaContainer > div.subareaUsersTab', cachedBox.chatBoxContentElem);
cachedBox.replaceHtml(theElement, theHtml);

cachedBox.hideUsersWaitBar();
cachedBox.setBoxDimensions();

theElement = null;

}, 300);
}
}


ChatBox.prototype.replaceTableUsers = function (theHtml) {

if (theHtml != '') {

var cachedBox = this;


window.self.clearTimeout(cachedBox.replaceUsersTimer);
cachedBox.replaceUsersTimer = window.self.setTimeout(function() {


var theElement = $('div.tableuserswrapper > div.outerborder > div.innerborder > div.userswrapper', cachedBox.chatBoxElem);
cachedBox.replaceHtml(theElement, theHtml);


var innerWrapper = $('div.tableuserswrapper > div.outerborder > div.innerborder > div.userswrapper', cachedBox.chatBoxElem);
var outerWrapper = $('div.tableuserswrapper', cachedBox.chatBoxElem);

innerWrapper.height(cachedBox._getTableUsersWrapperHeight());
outerWrapper.height(cachedBox._getTableUsersWrapperHeight(true));

innerWrapper = null;
outerWrapper = null;
}, 500);
}
}


ChatBox.prototype.replaceHtml = function(element, html) {

var oldElement = element[0];
if (oldElement && oldElement.parentNode) {

var newElement = oldElement.cloneNode(false);
newElement.innerHTML = html;

oldElement.parentNode.replaceChild(newElement, oldElement);



}


element.remove();

element = null;
oldElement = null;
newElement = null;
html = null;
};


ChatBox.prototype._getTableUsersWrapperHeight = function (addParentMarginsHeight) {

var noOfTableUsers = chatController._userHandler.getNumTableChatters();
if (noOfTableUsers == 0) {
return 0;
}

var userWrapperParentsMarginHeight = (this.isIE() ? 15 : 15);
var tableUsersHeaderHeight = 19;

var userRowHeight = 19;
var usersWrapperMaxHeight = (userRowHeight * 4) + tableUsersHeaderHeight;


var usersWrapperHeight = (userRowHeight * noOfTableUsers) + tableUsersHeaderHeight;
if (usersWrapperHeight > usersWrapperMaxHeight) {
usersWrapperHeight = usersWrapperMaxHeight;
}

if (addParentMarginsHeight) {
usersWrapperHeight += userWrapperParentsMarginHeight;
}
return usersWrapperHeight;
}


ChatBox.prototype.replaceRooms = function (theHtml) {

if (theHtml != '') {

var theElement = $('div.subareaContainer > div.subareaRoomsTab', this.chatBoxContentElem);
this.replaceHtml(theElement, theHtml);


if (!chatSettings.isMultiplayerChat()) {


window.setTimeout(function () {


theElement = $('div.subareaContainer > div.subareaRoomsTab', this.chatBoxContentElem);

var myRow = $('div.toggleBoxHeaderCurrent', this.chatBoxContentElem).closest('div.toggleBox');


theElement.scrollTo(myRow);
theElement.scrollTo('-=5px');
theElement.trigger('click');

myRow = null;
theElement = null;
}, 0);

}

this._addRoomRowEvents();
this.hideRoomsWaitBar();
}
}


ChatBox.prototype.showProfileWaitBar = function () {
var profileInfo = $('#chatProfileInfo', this.chatBoxContentElem);
var waitbar = $('#profileWaitBar', this.chatBoxContentElem);

profileInfo.hide();
waitbar.show();

profileInfo = null;
waitbar = null;
}

ChatBox.prototype.hideProfileWaitBar = function () {
var profileInfo = $('#chatProfileInfo', this.chatBoxContentElem);
var waitbar = $('#profileWaitBar', this.chatBoxContentElem);

profileInfo.show();
waitbar.hide();

profileInfo = null;
waitbar = null;
}


ChatBox.prototype.showUsersWaitBar = function () {
var usersBox = $('div.subareaContainer > div.subareaUsersTab > div.toggleBox', this.chatBoxContentElem);
var waitbar = $('#usersWaitBar', this.chatBoxContentElem);

usersBox.hide();
waitbar.show();

usersBox = null;
waitbar = null;
}

ChatBox.prototype.hideUsersWaitBar = function () {
var usersBox = $('div.subareaContainer > div.subareaUsersTab > div.toggleBox', this.chatBoxContentElem);
var waitbar = $('#usersWaitBar', this.chatBoxContentElem);

usersBox.show();
waitbar.hide();

usersBox = null;
waitbar = null;
}


ChatBox.prototype.showRoomsWaitBar = function () {
var roomsBox = $('div.subareaContainer > div.subareaRoomsTab > div.toggleBox', this.chatBoxContentElem);
var waitbar = $('#roomsWaitBar', this.chatBoxContentElem);

roomsBox.hide();
waitbar.show();

roomsBox = null;
waitbar = null;
}

ChatBox.prototype.hideRoomsWaitBar = function () {
var roomsBox = $('div.subareaContainer > div.subareaRoomsTab > div.toggleBox', this.chatBoxContentElem);
var waitbar = $('#roomsWaitBar', this.chatBoxContentElem);

roomsBox.show();
waitbar.hide();

roomsBox = null;
waitbar = null;
}


ChatBox.prototype.showLogoutLink = function () {
var linky = $('#chatLogoutLink', this.chatBoxElem);

linky.toggleClass('link11grey', true);
linky.toggleClass('link11lightgrey', false);

linky = null;
}

ChatBox.prototype.hideLogoutLink = function () {
var linky = $('#chatLogoutLink', this.chatBoxElem);

linky.toggleClass('link11grey', false);
linky.toggleClass('link11lightgrey', true);

linky = null;
}



ChatBox.prototype.scrollToBottom = function (chatArea) {

if (chatArea) {
var myself = this;

var scrolledUpHeight = chatArea.attr('scrollTop');
var visibleAreaHeight = chatArea.height();
var totalRowsHeight = 0;




var chatRows = $('div.chatRow', chatArea);
chatRows.each(function () {

var myHeight = $(this).height();
if (!isNaN(myHeight)) {
totalRowsHeight += myHeight;
}

});



var unscrolledPart = totalRowsHeight - (scrolledUpHeight + visibleAreaHeight);

if (unscrolledPart > 0 && unscrolledPart < 200) {
chatArea.scrollTop(chatArea.attr('scrollHeight'));
}
chatRows = null;
}
}



ChatBox.prototype.drawNongameProfileInfo = function (profileInfoObject) {

var cachedChatController = chatController;
var theUserHandler = cachedChatController._userHandler;
var theBox = this;


if (!theUserHandler.profileInfoRedrawBlocked()) {
theUserHandler.blockProfileInfoRedraw();

if (profileInfoObject) {


profileInfoObject.userID;
profileInfoObject.username;
profileInfoObject.age;
profileInfoObject.gender;
profileInfoObject.starsign;
profileInfoObject.region;
profileInfoObject.relationship;
profileInfoObject.partnersearch;
profileInfoObject.membersince;
profileInfoObject.isVip;
profileInfoObject.lastlogon;
profileInfoObject.noOfFriends;
profileInfoObject.country;
profileInfoObject.profileImage;

var isMale = profileInfoObject.gender == 'm';

var subareaProfileTab = $('#chatProfileInfo', theBox.chatBoxContentElem);


$('#chatProfileImageElem', subareaProfileTab).attr({src : profileInfoObject.profileImage, alt : profileInfoObject.username});


var chatIconHtml = '';
var chatUserObject = theUserHandler.getChatter(profileInfoObject.username);
if (chatUserObject) {
var chatIconHtml = theUserHandler.getChatIconHtml(chatUserObject._javaUserObject);
}

var chatIconElement = $('div.rightUserLinks > div.userIcon > div.leftUsericon', subareaProfileTab);
this.replaceHtml(chatIconElement, chatIconHtml);


var rightUsernameLink = $('div.rightUsername > a', subareaProfileTab);
rightUsernameLink.text(profileInfoObject.username);
rightUsernameLink.removeClass('link14profileblue link14profilered');
rightUsernameLink.addClass(profileInfoObject.gender == 'm' ? 'link14profileblue' : 'link14profilered');


$('div.infoRowsWrapper > div.infoRow', subareaProfileTab).hide();


if (profileInfoObject.membersince.length > 0) {
$('#infoRowMemberSince > div.rightSide', subareaProfileTab).text(profileInfoObject.membersince);
$('#infoRowMemberSince', subareaProfileTab).show();
}


if (profileInfoObject.age.length > 0) {
$('#infoRowAge > div.rightSide', subareaProfileTab).text(profileInfoObject.age);
$('#infoRowAge', subareaProfileTab).show();
}


if (profileInfoObject.region.length > 0) {
$('#infoRowLocation > div.rightSide', subareaProfileTab).text(profileInfoObject.region);
$('#infoRowLocation', subareaProfileTab).show();
}


if (profileInfoObject.relationship.length > 0) {
$('#infoRowRelationship > div.rightSide', subareaProfileTab).text(profileInfoObject.relationship);
$('#infoRowRelationship', subareaProfileTab).show();
}


if (profileInfoObject.partnersearch.length > 0) {
$('#infoRowPartnersearch > div.rightSide', subareaProfileTab).text(profileInfoObject.partnersearch);
$('#infoRowPartnersearch', subareaProfileTab).show();
}


if (profileInfoObject.country.length > 0) {
$('#infoRowCountry > div.rightSide', subareaProfileTab).text(profileInfoObject.country);
$('#infoRowCountry', subareaProfileTab).show();
}


if (profileInfoObject.noOfFriends > 0) {
$('#infoRowFriends > div.rightSide', subareaProfileTab).text(profileInfoObject.noOfFriends);
$('#infoRowFriends', subareaProfileTab).show();
}




$('div.rightUsername > a, #longLinkToProfile, #chatProfileImageWrapper', subareaProfileTab).unbind();
$('#actionPrivateChat', subareaProfileTab).unbind().hide();
$('#actionShowGuestbook', subareaProfileTab).unbind();
$('#actionIgnore', subareaProfileTab).unbind().hide();
$('#actionBan', subareaProfileTab).unbind().hide();
$('#actionKick', subareaProfileTab).unbind().hide();
$('#actionMute', subareaProfileTab).unbind().hide();
$('#actionIncarcerate', subareaProfileTab).unbind().hide();
$('#actionRelease', subareaProfileTab).unbind().hide();




$('div.rightUsername > a, #longLinkToProfile, #chatProfileImageWrapper', subareaProfileTab).bind('click', function () {
var url = '/profile/myprofile/profile.php?profile=' + profileInfoObject.username + '&tmp_username=' + profileInfoObject.username + '&link_game=true';
cachedChatController._replaceParentWindow(url);
});


$('#actionShowGuestbook', subareaProfileTab).bind('click', function () {
var url = '/profile/guestbook/?profile=' + profileInfoObject.username + '&tmp_username=' + profileInfoObject.username + '&link_game=true';
cachedChatController._replaceParentWindow(url);
});




var ownUserObject = cachedChatController._userHandler.getCurrent()._chatUserObject;
if (profileInfoObject.username != ownUserObject.getName() && !chatSettings.isInstantMessenger()) {


if (chatSettings.isSingleplayerChat() && !cachedChatController._roomHandler.isJailRoom() && !cachedChatController._roomHandler.hasPrivateChatWith(profileInfoObject.username)) {
$('#actionPrivateChat', subareaProfileTab).show().bind('click', function () {

chatController.beginPrivateChat(profileInfoObject.username);
});
}
if (!theUserHandler.getCurrent().ignoresUser(profileInfoObject.username)) {
$('#actionIgnore', subareaProfileTab).show().bind('click', function () {

if (cachedChatController.handleIgnore(profileInfoObject.username)) {
theBox.hideProfileTab();
toggleToChatBox();
}
});
}



if (ownUserObject.isMuteAdm()) {
$('#actionMute', subareaProfileTab).show().bind('click', function () {

if (cachedChatController.handleMute(profileInfoObject.username)) {
theBox.hideProfileTab();
toggleToChatBox();
}
});
}
if (ownUserObject.isKickAdm()) {
$('#actionKick', subareaProfileTab).show().bind('click', function () {

if (cachedChatController.handleKick(profileInfoObject.username)) {
theBox.hideProfileTab();
toggleToChatBox();
}
});
}
if (ownUserObject.isBanAdm()) {
$('#actionBan', subareaProfileTab).show().bind('click', function () {

if (cachedChatController.handleBan(profileInfoObject.username)) {
theBox.hideProfileTab();
toggleToChatBox();
}
});


if (profileInfoObject.isInmate) {
$('#actionRelease', subareaProfileTab).show().bind('click', function () {
cachedChatController.handleReleaseFromJail(profileInfoObject.username);
});

} else {
$('#actionIncarcerate', subareaProfileTab).show().bind('click', function () {
cachedChatController.handleIncarceration(profileInfoObject.username);
});
}
}
}

}
}


this.hideProfileWaitBar();
}


ChatBox.prototype.showIMInviteBox = function(sendingJavaUserObject, senderUsername, senderIsMale, senderIsVip, roomName) {


var msgHolder = $('#imPopupHolder', this.chatBoxContentElem);

if (msgHolder.length) {
var myPopupWrapper = $('#chatIMPopup' + roomName, msgHolder);

if (!myPopupWrapper.length) {

msgHolder.append('<div id="chatIMPopup' + roomName + '" class="chatIMPopup"></div>');

myPopupWrapper = $('#chatIMPopup' + roomName, msgHolder);

if (myPopupWrapper.length) {

myPopupWrapper.html('<div class="borderLiner"><div class="lightLine"></div><div class="headerBar"><div class="iconWrapper chatIMPopupIcon">...</div><span class="size12white chatIMPopupUsername"><strong>...</strong></span><div class="closeIconWrapper "><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -271px;"></div></div></div></div><div class="bodyBox"><div class="profilePicWrapper"><div class="profilePicBorder"><img src="..." width="64" height="49" alt="" /></div><div class="profilePicBottomBorder"></div></div><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -109px;"></div></div><div class="chatIMPopupMessage size12white">...</div><div style="clear:both;"></div></div></div>');

var globalChatboxCopy = this;
var cachedIMController = imChatController;
var cachedChatVars = chatVars;
var cachedChatController = chatController;


$('div.closeIconWrapper', myPopupWrapper).unbind().click(function() {

cachedChatController._server.imDeclineInvitation(sendingJavaUserObject, roomName);
myPopupWrapper.hide();


if (cachedIMController) {

cachedIMController.removeFromIMsPending(roomName);
cachedIMController.uncacheMessages(cachedChatVars.mbp, roomName);
cachedIMController.showIMsPending();
}
});


var chatIconHtml = cachedChatController._userHandler.getChatIconHtml(sendingJavaUserObject);
var iconElem = $('div.chatIMPopupIcon', myPopupWrapper);
iconElem.html(chatIconHtml);


$('span.chatIMPopupUsername strong', myPopupWrapper).text(senderUsername);


cachedChatController.replaceImPopupProfilePicUrl(senderUsername, myPopupWrapper);


var replacementText = senderUsername + " har sendt dig en direkte besked. " + '<span class="underlined">' + "Klik her</span>";
var theMessageElem = $('div.chatIMPopupMessage', myPopupWrapper);
theMessageElem.html(replacementText)


.unbind().click(function() {

if (cachedIMController) {
cachedIMController.openImWindow(senderUsername, cachedChatVars.mbp);
}

cachedChatController._server.imAcceptInvitation(sendingJavaUserObject, roomName);

myPopupWrapper.slideUp(300);


if (cachedIMController) {
cachedIMController.removeFromIMsPending(roomName);

cachedIMController.showIMsPending();
}
});
}
}

if (myPopupWrapper.length) {


msgHolder.css('bottom', '80px');
myPopupWrapper.slideDown(1500);
}
}
}





function toggleToSomeBox(whichBox) {
$(document).ready(function() {

var cachedChatController = chatController;
var theBox = cachedChatController._box;


if (whichBox != 'settingsChaticons') {
cachedChatController.requestChatIconIDchange();
}


if (!cachedChatController.isLoggedOut()) {


var headerBar = $('#chatbox > div.outerbox > div.lightborder > div.darkborder > div.headerbar');
var firstBacklink = $('div.submenuwrapperChat > div.backLink:first', headerBar);
var allSubmenus = $('div.submenuwrapper', headerBar);
var allSubareaContainers = $('#chatboxContentWrapper div.subareaContainer');
var allSubareas = $('div.subareaContainer > div.subarea', theBox.chatBoxContentElem);
var multiplayerTableUsersWrapper = $('div.tableuserswrapper', theBox.chatBoxElem);


firstBacklink.hide();
allSubmenus.hide();
allSubareaContainers.hide();
allSubareas.hide();
multiplayerTableUsersWrapper.hide();

var myMenuItem, mySubmenu, mySubareaContainer, mySubarea;


if (whichBox == 'chat') {

myMenuItem = $('div.menuitem:first', theBox.chatBoxElem);
mySubmenu = $('div.submenuwrapperChat',headerBar);
mySubareaContainer = $('#chatboxContentWrapper div.subareaContainer:first');
mySubarea = $('#chatboxContentWrapper div.subareaContainer > div.subareaChatTab');


theBox.switchToSubarea('subareaChatTab');

if (cachedChatController._roomHandler.multiplayerTableRoomJoined()) {
multiplayerTableUsersWrapper.show();
}

} else if (whichBox == 'profile') {

myMenuItem = $('div.menuitem:first', theBox.chatBoxElem).next();
mySubmenu = $('div.submenuwrapperProfile', headerBar);
mySubareaContainer = $('#chatboxContentWrapper div.subareaContainer:first').next();
mySubarea = $('#chatboxContentWrapper > div.subareaContainer > div.subareaProfileTab');

myMenuItem.show();

} else if (whichBox == 'loggedout') {

mySubmenu = $('div.submenuwrapperLoggedout', headerBar);
mySubareaContainer = $('#chatboxContentWrapper div.subareaContainer:first').next().next();
mySubarea = $('#chatboxContentWrapper > div.subareaContainer > div.subareaLoggedoutTab');

globalThemeboxMenuitemToggler.hideAll();

} else if (whichBox == 'settingsGeneral') {

theBox.freezeWrenchIconBG = true;

myMenuItem = $('#chatheadericonWrench > div.bg', theBox.chatBoxElem);

mySubmenu = $('div.submenuwrapperSettingsGeneral', headerBar);
mySubareaContainer = $('#chatboxContentWrapper div.subareaContainer:first').next().next().next();
mySubarea = $('#chatboxContentWrapper > div.subareaContainer > div.subareaSettingsGeneralTab');

globalThemeboxMenuitemToggler.hideAll();
myMenuItem.show();

} else if (whichBox == 'settingsChaticons') {

theBox.freezeWrenchIconBG = true;


var ownUser = cachedChatController._userHandler.getCurrent();
if (ownUser) {
var existingChatIconID = cachedChatController._userHandler.getChatIconID(ownUser._chatUserObject._javaUserObject);
theBox.replaceCurrentChatIconHtml(existingChatIconID);
}



myMenuItem = $('#chatheadericonWrench > div.bg', theBox.chatBoxElem);
mySubmenu = $('div.submenuwrapperSettingsChaticons', headerBar);
mySubareaContainer = $('#chatboxContentWrapper div.subareaContainer:first').next().next().next();
mySubarea = $('#chatboxContentWrapper > div.subareaContainer > div.subareaSettingsChaticonsTab');

globalThemeboxMenuitemToggler.hideAll();
myMenuItem.show();
}


if (mySubmenu && mySubmenu.length) {
mySubmenu.show();
}
if (mySubareaContainer && mySubareaContainer.length) {
mySubareaContainer.show();
}
if (mySubarea && mySubarea.length) {
mySubarea.show();
}

if (whichBox == 'settingsGeneral' || whichBox == 'settingsChaticons') {

mySubarea.attr('scrollTop', 0);

} else {


theBox.freezeWrenchIconBG = false;

var wrenchIconTabBG = $('#chatheadericonWrench', theBox.chatBoxElem).children(':first');
wrenchIconTabBG.hide();
wrenchIconTabBG = null;



if (myMenuItem && myMenuItem.length) {
globalThemeboxMenuitemToggler.switchTo(myMenuItem);
}
}


headerBar = null;
firstBacklink = null;
allSubmenus = null;
allSubareaContainers = null;
multiplayerTableUsersWrapper = null;
myMenuItem = null;
mySubmenu = null;
mySubareaContainer = null;
mySubarea = null;
}
});
}

function toggleToChatBox() {
toggleToSomeBox('chat');
}

function toggleToProfileBox() {
toggleToSomeBox('profile');
}

function toggleToLoggedoutBox() {
toggleToSomeBox('loggedout');
}

function toggleToSettingsGeneralBox() {
toggleToSomeBox('settingsGeneral');
}

function toggleToSettingsChaticonsBox() {
toggleToSomeBox('settingsChaticons');
}




ChatMessage.prototype._outgoingMessagesBlocked = false;
ChatMessage.prototype._outgoingMessagesDenied = false;

ChatMessage.prototype._messageSentTimes = new Array();
ChatMessage.prototype._messageSpamInterval = 9*1000;
ChatMessage.prototype._messageSpamQuota = 3;
ChatMessage.prototype._whiteSpaceRegex = /\((.{0,5}?)(\s+?)(.{0,5}?)\)/g;

ChatMessage.prototype._badWords = chatVars.badWordsArray;
ChatMessage.prototype._niceWords = chatVars.niceWordsArray;
ChatMessage.prototype._badMessages = new Array();


function ChatMessage() {
var toolies = chatTools;


for (var index in this._badWords) {
var prettyBadWord = toolies.chromeRims(this._badWords[index]);

if (prettyBadWord.length > 0) {
this._badWords[index] = new RegExp("((^.{0}?)|[^a-zA-Z]+?)(" + prettyBadWord + ")([^a-zA-Z]+?|(.{0}?$))", "gi");
}
}
}


ChatMessage.prototype.buildInfoMessage = function(theMessage, coloured) {

theMessage = this._wordwrap(theMessage);

var textClass = (coloured ? 'size11red' : 'size11darkgrey');

var stringsAr = new Array('<div class="chatRow chatRowInfoMessage ',
textClass,
'"><div class="chatIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -109px;"></div></div></div><strong>',
this._drawTimeText(),
theMessage,
'</strong></div>');
return stringsAr.join('');
};


ChatMessage.prototype.buildUserMessage = function (theMessage, javaSenderUserObject) {

if (javaSenderUserObject != undefined) {
var theController = chatController;

var isMale = javaSenderUserObject.isMale();
var linkClass = theController._userHandler.getLinkClassFromGender(isMale);

theMessage = chatTools._encodeString(theMessage);
  theMessage = theController._smileyHandler.swapSmileyPlaceholders(theMessage, true);

var chatIconHtml = theController._userHandler.getChatIconHtml(javaSenderUserObject);

var stringsAr = new Array('<div class="chatRow',
(isMale ? ' chatRowMale' : ' chatRowFemale'),
'"><div class="chatIcon">',
chatIconHtml,
'</div><span class="chatName"><span class="',
linkClass,
'"><strong>',
javaSenderUserObject.getName(),
':</strong></span></span> ',
this._drawTimeText(),
theMessage,
'</div>');
return stringsAr.join('');
}
};




ChatMessage.prototype.buildMeUserMessage = function (theMessage, javaSenderUserObject) {
if (javaSenderUserObject != undefined) {

var theController = chatController;

var isMale = javaSenderUserObject.isMale();
var linkClass = theController._userHandler.getLinkClassFromGender(isMale);

theMessage = theMessage.replace('/me ', '');

theMessage = chatTools._encodeString(theMessage);
  theMessage = theController._smileyHandler.swapSmileyPlaceholders(theMessage, true);

var chatIconHtml = theController._userHandler.getChatIconHtml(javaSenderUserObject);

var stringsAr = new Array('<div class="chatRow"><div class="chatIcon">',
chatIconHtml,
'</div><span class="chatName"><span class="',
linkClass,
'"><strong>',
javaSenderUserObject.getName(),
':</strong></span></span> ',
this._drawTimeText(),
'<span class="meMessage"><strong>',
theMessage,
'</strong></span></div>');
return stringsAr.join('');
}
}


ChatMessage.prototype.buildAdminUserMessage = function (theMessage, javaSenderUserObject) {
if (javaSenderUserObject != undefined) {

var theController = chatController;

var isMale = javaSenderUserObject.isMale();
var linkClass = theController._userHandler.getLinkClassFromGender(isMale);

theMessage = theMessage.replace('/admin ', '');

theMessage = chatTools._encodeString(theMessage);
  theMessage = theController._smileyHandler.swapSmileyPlaceholders(theMessage, true);

var chatIconHtml = theController._userHandler.getChatIconHtml(javaSenderUserObject);

var stringsAr = new Array('<div class="chatRow chatRowAdminMessage"><div class="innerWrapper"><div class="chatIcon">',
chatIconHtml,
'</div><span class="chatName"><span class="',
linkClass,
'"><strong>',
javaSenderUserObject.getName(),
" (admin):</strong></span></span> ",
this._drawTimeText(),
'<span class="adminMessage"><strong>',
theMessage,
'</strong></span></div></div>');
return stringsAr.join('');
}
}


ChatMessage.prototype.buildAIRedboxMessage = function (theMessage) {

var theController = chatController;

theMessage = this._wordwrap(theMessage);
theMessage = chatTools._encodeString(theMessage);
  theMessage = theController._smileyHandler.swapSmileyPlaceholders(theMessage, true);

var stringsAr = new Array('<div class="chatRow chatRowAIGameMessage"><div class="innerWrapper">',
this._drawTimeText(),
'<span class="AIGameMessage"><strong>',
theMessage,
'</strong></span></div></div>');
return stringsAr.join('');
}


ChatMessage.prototype.buildAIPlayerMessage = function (senderName, theMessage) {

var theController = chatController;

var nameText = (senderName == null ? '' : '<span class="size11darkgrey"><strong>' + senderName + ':</strong></span>');

theMessage = chatTools._encodeString(theMessage);
  theMessage = theController._smileyHandler.swapSmileyPlaceholders(theMessage, true);

var stringsAr = new Array('<div class="chatRow"><div class="innerWrapper"><div class="chatIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-661px -73px;"></div></div></div>',
nameText,
this._drawTimeText(),
theMessage,
'</div></div>');
return stringsAr.join('');
}


ChatMessage.prototype.buildBankStreamedMessage = function (theMessage) {

var theUserHandler = chatController._userHandler;


theMessage = theMessage.replace('/bank ', '');


var userGenderString = theMessage.substring(0, 2);
if (userGenderString == 'm_' || userGenderString == 'k_') {
theMessage = theMessage.substr(2);
} else {
userGenderString = false;
}


var indexOfFirstSpace = theMessage.indexOf(' ');
var username = theMessage.substring(0, indexOfFirstSpace);
theMessage = theMessage.substr(indexOfFirstSpace + 1);


var userTicket = '';
var splitty = theMessage.split('_');
if (splitty.length == 3) {
var bankID = splitty[1];
var last4 = splitty[2];

var userTicketID = bankID  + '_' + last4  + '_' + chatVars.uid

var userTicketLinkHtml = '<a class="prizeShareLink link12blue" id="' + userTicketID + '"><strong>' + "Klik her for 5% side-gevinst!" + '</strong></a>';
//var userTicketLinkHtml = '<div class="prizeShareLink" id="' + userTicketID + '"></div>';
}
theMessage = splitty[0];


if (userGenderString && theUserHandler.getChatter(username)) {

var userIsMale = (userGenderString == 'm_');
var genderTextClass = theUserHandler.getLinkClassFromGender(userIsMale);
var usernameLinkHtmlAr = new Array('<span class="chatName ', genderTextClass, '"><span><strong>', username, '</strong></span></span> ');

theMessage = (usernameLinkHtmlAr.join('') + '<strong>' + theMessage + '</strong>');

} else {
theMessage = ('<strong>' + (username + ' ' + theMessage) + '</strong>');
}


var stringsAr = new Array(
'<div class="chatRow chatRowBankBox"><div class="innerWrapper"><div class="bankBoxHeader"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-461px -415px;"></div></div><div class="bankBoxHeaderText">&nbsp;<strong>',
"Bank vundet!",
'</strong></div><div style="clear:both;"></div></div><div class="bankBoxBody"><img class="chatbankwon" src="http://www.komogvind.dk/images/icons24/chat_bankwon.png" /><strong>',
"Bank vundet!",
'</strong><br /><span class="size11black">',
theMessage,
'</span>',
userTicketLinkHtml,
'</div><div style="clear:both;"></div></div></div>'
);
return stringsAr.join('');
}


ChatMessage.prototype.buildJackpotStreamedMessage = function (theMessage, typeStr) {

switch(typeStr) {

case 'super':
theMessage = theMessage.replace('/superjackpot', '');
var icon = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-401px -235px;"></div></div>';
var textString = "SuperJackpotten";
var textClass = 'superjackpotMessage';
break;

case 'extra':
theMessage = theMessage.replace('/extrajackpot', '');
var icon = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-381px -235px;"></div></div>';
var textString = "ExtraJackpotten";
var textClass = 'extrajackpotMessage';
break;

case 'quick':
default:
theMessage = theMessage.replace('/quickjackpot', '');
var icon = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-361px -235px;"></div></div>';
var textString = "QuickJackpotten";
var textClass = 'quickjackpotMessage';
break;
}



theMessage = jQuery.trim(theMessage);
var threeStrings = theMessage.split(' ');
var username = threeStrings[2];
var currency = threeStrings[1];
var amount = threeStrings[0];



var stringsAr = new Array (
'<div class="chatRow chatRowJackpotMessage"><div class="innerWrapper"><strong>',
username,
'</strong> ',
"har vundet",
' <strong><span class="',
textClass,
'">',
textString,
'</span></strong> ',
"på ialt",
' <strong>',
currency,
' ',
amount,
"</strong>, tillykke!</div></div>"
);
return stringsAr.join('');
}


ChatMessage.prototype.buildFriendsInRoomMessage = function (theFriends) {

if (theFriends.length > 1) {

var textString = "Dine venner __DO_NOT_TRANSLATE__ er også online i dette rum ";
var lastFriendString = " og" + ' <span class="chatName"><span>' + jQuery.trim(theFriends.pop().getName()) + '</span></span>';

} else {

var textString = "Din ven __DO_NOT_TRANSLATE__ er også online i dette rum ";
var lastFriendString = '';
}

var usernameLinkArray = new Array();
for (var index in theFriends) {

var friend = theFriends[index];
var usernameLink = ' <span class="chatName"><span>' + jQuery.trim(friend.getName()) + '</span></span>';

usernameLinkArray.push(usernameLink);
}
var replacement = usernameLinkArray.join(',') + lastFriendString;

return this.buildInfoMessage(textString.replace('__DO_NOT_TRANSLATE__', replacement));
}


ChatMessage.prototype.buildChatNewsMessage = function (incomingStreamMessage, undeletable) {

var iconString = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-221px -415px;"></div></div>';
var prefixString = '/chatNews ';
var newsText = ( incomingStreamMessage.indexOf(prefixString) > -1 ? incomingStreamMessage.substr(prefixString.length) : incomingStreamMessage);

var closeIconPart = (undeletable ? '</div><div class="newsText">' : '</div><div class="closeIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-601px -271px;"></div></div></div><div class="newsText">');

var stringsAr = new Array(
'<div class="chatNewsTab"><div class="chatNewsTabBG"></div><div class="leftIcon">',
iconString,
closeIconPart,
newsText,
'</div></div>'
);
return stringsAr.join('');
}


ChatMessage.prototype.drawBadgeMessage = function (roomName) {

var theBox = chatController._box;


$('#badgeBoxWrapper', theBox.chatBoxContentElem).remove();


theBox.addChatRow('<div class="chatRow chatRowBadgeBox" id="badgeBoxWrapper"></div>');


$('#badgeBoxWrapper', theBox.chatBoxContentElem).load('http://www.komogvind.dk/ajax/chat_ajax_badge.php', {userid : chatVars.uid, gamename : chatVars.gameName, gid : chatVars.gameID}, function () {
$(this).show();

var chatArea = theBox.getChatArea(roomName);
theBox.scrollToBottom(chatArea);
});
}


ChatMessage.prototype.buildJailJoinMessage = function (roomName, inmateVersion) {
var theBox = chatController._box;


$('#jailBoxWrapper', theBox.chatBoxContentElem).remove();


var text = (inmateVersion ? "Du er nu i fængsel, og vil blive løsladt når ovenstående tid løber ud. Indtil da kan du ikke skifte rum. Vil du vide mere om hvordan fængslet fungerer?" : "Du er nu i fængsel som gæst, men kan til enhver tid skifte til et andet rum. Vil du vide mere om, hvordan fængslet fungerer?");

var stringsAr = new Array (
'<div class="chatRow chatRowJailBox" id="jailBoxWrapper"><div class="innerWrapper"><div class="jailBoxHeader"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-221px -415px;"></div></div><div class="jailBoxHeaderText">&nbsp;<strong>I FÆNGSEL</strong></div><div style="clear:both;"></div></div><div class="jailBoxBody size11black">',
text,
'<a href="http://www.komogvind.dk/help/chatguide.php" target="_blank">',
"Læs mere her</a></div></div></div>"
);
return stringsAr.join('');
}


ChatMessage.prototype._drawTimeText = function () {

if (chatSettings.isInstantMessenger()) {

var date = new Date();

var hours = '' + date.getHours();
if (hours.length == 1) {
hours = '0' + hours;
}

var minutes = '' + date.getMinutes();
if (minutes.length == 1) {
minutes = '0' + minutes;
}

var stringsAr = new Array (
' <span class="size11darkgrey"><strong><span class="timeWrapper">(',
hours,
':',
minutes,
')</span></strong></span> '
);
return stringsAr.join('');
}
return '';
}


ChatMessage.prototype._wordwrap = function (theMessage) {


var theMessage = new String(theMessage);
var chunks = theMessage.split(' ');
var maxChars = 23;
var newMessage = '';

var chunkyLength = chunks.length;
for (var index = 0; index < chunkyLength; index++) {
var chunk = chunks[index];
if (chunk.length > maxChars) {

var noOfSubChunks = (chunk.length / maxChars);
var chunkSize = chunk.length;
var subChunkIndex = 0;

while (subChunkIndex < noOfSubChunks) {

var charOffset = subChunkIndex*maxChars;

if (subChunkIndex == 0) {
newMessage += ' ';
}

if (chunkSize < 15) {
newMessage += chunk.substr(charOffset, chunkSize);
} else {
newMessage += chunk.substr(charOffset, maxChars) + ' ';
chunkSize -= maxChars;
}
subChunkIndex++;
}
} else {
newMessage += ' ' + chunk;
}
}


var counter = 5;
while (counter-- > 0) {
newMessage = newMessage.replace(this._whiteSpaceRegex, "($1$3)$2");
newMessage = newMessage.replace('( ', '(');
newMessage = newMessage.replace(' )', ')');
}
return newMessage;
}

ChatMessage.prototype.filterBadWords = function (origMessage) {

var niceWords = this._niceWords;
var theLength = this._badWords.length;

var changesMade = false;
var alteredMessage = origMessage;

if (!chatController._roomHandler.isJailRoom()) {

for (var index = 0; index < theLength; index++) {

var badRegExp = this._badWords[index];

var thisNiceWord = niceWords[ Math.floor(Math.random() * niceWords.length) ];
alteredMessage = alteredMessage.replace(badRegExp, '$2 ' + thisNiceWord + '$4');

if (!changesMade && alteredMessage != origMessage) {
changesMade = true;
}
}


if (changesMade) {
this._badMessages.push(origMessage);
}
}
return alteredMessage;
}


ChatMessage.prototype.getLastBadMessage = function () {

var badMessage = '';
if (this._badMessages.length > 0) {
badMessage = this._badMessages.shift();
}
return badMessage;
}


ChatMessage.prototype.isTextCommand = function (theMessage) {
return theMessage.indexOf('/') == 0;
};


ChatMessage.prototype.isKickCommand = function (theMessage) {
return theMessage.indexOf('/kick') == 0;
};
ChatMessage.prototype.isMuteCommand = function (theMessage) {
return theMessage.indexOf('/mute') == 0;
};
ChatMessage.prototype.isIgnoreCommand = function (theMessage) {
return theMessage.indexOf('/ignore') == 0;
};
ChatMessage.prototype.isBanCommand = function (theMessage) {
return theMessage.indexOf('/ban') == 0;
};
ChatMessage.prototype.isMeCommand = function (theMessage) {
return theMessage.indexOf('/me') == 0;
};
ChatMessage.prototype.isAdminCommand = function (theMessage) {
return theMessage.indexOf('/admin') == 0;
};
ChatMessage.prototype.isJavascriptCommand = function (theMessage) {
return theMessage.indexOf('/javascript') == 0;
};
ChatMessage.prototype.isJailCommand = function (theMessage) {
return theMessage.indexOf('/prison') == 0;
};


ChatMessage.prototype.extractUsername = function (theMessage, commandName) {

var username;


switch (commandName) {
case 'jail' :
var command = '/prison ';break;
case 'mute' :
var command = '/mute ';break;
case 'kick' :
var command = '/kick ';break;
case 'ban' :
var command = '/ban ';break;
case 'ignore' :
var command = '/ignore ';break;
case 'javascript' :
var command = '/javascript ';break;
default:
return false;
}


var noCommand = theMessage.replace(command, '');
var spaceIndex = noCommand.indexOf(' ');

if (spaceIndex > -1) {
username = noCommand.substr(0, spaceIndex);
} else {
username = noCommand;
}
return username;
}


ChatMessage.prototype.extractScript = function (theMessage) {
var noCommand = theMessage.replace('/javascript ', '');
var spaceIndex = noCommand.indexOf(' ');
return noCommand.substr(spaceIndex + 1);
}


ChatMessage.prototype.isValid = function (theMessage) {

var maxMessageSize = chatSettings.getMaxMessageSize();
var messageSize = theMessage.length;

return (messageSize > 0 && messageSize <= maxMessageSize);
}



ChatMessage.prototype.isSpamming = function() {



var theDater = new Date();
var rightNow = theDater.getTime();


this._messageSentTimes.push(rightNow);


if (this._messageSentTimes.length > this._messageSpamQuota) {


var oldestTime = this._messageSentTimes.shift();


if ((rightNow - oldestTime) < this._messageSpamInterval) {

this.denyOutgoingMessages();


} else if (this._outgoingMessagesDenied) {
this._outgoingMessagesDenied = false;
}
}

return this.outgoingMessagesDenied();

}


ChatMessage.prototype.outgoingMessagesBlocked = function() {
return (this._outgoingMessagesBlocked);
}


ChatMessage.prototype.outgoingMessagesDenied = function() {
return (this._outgoingMessagesDenied);
}


ChatMessage.prototype.blockOutgoingMessages = function () {
this._outgoingMessagesBlocked = true;


window.self.setTimeout('chatController._message.unblockOutgoingMessages()', 500);
}


ChatMessage.prototype.unblockOutgoingMessages = function() {

if (!this._outgoingMessagesDenied) {
this._outgoingMessagesBlocked = false;
}
}


ChatMessage.prototype.denyOutgoingMessages = function () {
this._outgoingMessagesDenied = true;
}





ChatServer.prototype.CONNECT_ALLOWED = true;


ChatServer.prototype._serverArray;
ChatServer.prototype._initialServerIndex = undefined;
ChatServer.prototype._currentServerIndex = undefined;

ChatServer.prototype._httpBypassPorts = new Array('25000', '8080', '21');
ChatServer.prototype._httpBypassPortCount = 0;

ChatServer.prototype._connectTimeout = 10000;



ChatServer.prototype._connectionEverEstablished = false;


ChatServer.prototype._allServersTried = false;


function ChatServer() {}


ChatServer.prototype._getServerIndex = function (returnInitialIndex) {

if(this._initialServerIndex == undefined) {
this._initialServerIndex = chatTools.getHashcode(chatVars.defaultRoomName) % this._getNoOfServers();
}

var regex = /^[0-9]+$/;
var isNumeric = regex.test(this._currentServerIndex);
if(!isNumeric) {
this._currentServerIndex = this._initialServerIndex;
}



if(returnInitialIndex == true) {
return this._initialServerIndex;
}
return this._currentServerIndex;
}


ChatServer.prototype._moveServerIndex = function () {
this._currentServerIndex = (this._currentServerIndex + 1) % this._getNoOfServers();
}


ChatServer.prototype._getCurrentPort = function () {
var servers = this._getServers();
return servers[this._getServerIndex()];
}

ChatServer.prototype._getInitialPort = function () {
var servers = this._getServers();
return servers[this._initialServerIndex];
}

ChatServer.prototype._isUsingInitialIndex = function () {
return (this._getServerIndex() == this._getServerIndex(true));
}


ChatServer.prototype._getNoOfServers = function() {
return this._getServers().length;
}


ChatServer.prototype._getServers = function() {

if (this._serverArray == undefined)  {
this._serverArray = chatVars.serverPortArray;
}
return this._serverArray;
}


ChatServer.prototype._connectionWasEstablished = function () {
this._allServersTried = false;
this._connectionEverEstablished = true;
}

ChatServer.prototype._wasConnectionEverEstablished = function () {
return this._connectionEverEstablished;
}


ChatServer.prototype._incrementConnectTimeout = function () {
if (this._connectTimeout < 120000) {
this._connectTimeout += this._connectTimeout;
}
}





ChatServer.prototype.connect = function() {

if (this.CONNECT_ALLOWED) {
document.chatApplet.connect(this._getCurrentPort());
}
};


ChatServer.prototype.refuseConnection = function () {
document.chatApplet.disconnect();
this.CONNECT_ALLOWED = false;
}

ChatServer.prototype.allowConnection = function () {
this.CONNECT_ALLOWED = true;
}


ChatServer.prototype.reConnect = function (errorMessage) {


try {

if (this && this.CONNECT_ALLOWED && document.chatApplet && !document.chatApplet.isConnected()) {

var theController = chatController;


this._moveServerIndex();


if (!this._isUsingInitialIndex()) {


this._allServersTried = true;


var cachedServer = this;
window.setTimeout(function(){cachedServer.connect();}, 500);


} else if (this._allServersTried) {


theController._box.addChatRow(theController._message.buildInfoMessage(errorMessage));


if (!this._wasConnectionEverEstablished()) {


if (this._httpBypassPortCount < this._httpBypassPorts.length) {


theController._box.addChatRow(theController._message.buildInfoMessage("Forbinder via HTTP..."));


var thePort = this._httpBypassPorts[this._httpBypassPortCount];
var tunnelID = this._getInitialPort();
var bypassID = 1;
document.chatApplet.connectHTTP(thePort, tunnelID, bypassID);

this._httpBypassPortCount++;


} else {

this._httpBypassPortCount = 0;
this._allServersTried = false;


window.setTimeout('chatController.connect()', this._connectTimeout);


this._incrementConnectTimeout();
}


} else {


window.setTimeout('chatController.connect()', this._connectTimeout);


this._incrementConnectTimeout();
}
}
}
} catch(e) {}
}


ChatServer.prototype.authenticate = function () {

if (document.chatApplet.isConnected()) {

this._connectionWasEstablished();
document.chatApplet.authenticate();
}
}


ChatServer.prototype.requestPersistentRoomList = function () {
document.chatApplet.requestPersistentRoomList();
}


ChatServer.prototype.leaveRoom = function (roomName) {
document.chatApplet.leave(roomName);
}


ChatServer.prototype.enterRoom = function (roomName) {
document.chatApplet.join(roomName);
}


ChatServer.prototype.sendOutgoingMessage = function (theMessage, roomName) {
if (roomName != undefined) {
document.chatApplet.chat(theMessage, roomName);
}
}


ChatServer.prototype.getMaxMessageSize = function () {
return document.chatApplet.getMaxMessageSize();
}




ChatServer.prototype.getUsersInRoom = function (roomName) {
return document.chatApplet.getUsersInRoom(roomName);
}


ChatServer.prototype.getJavaUserObject = function (username) {
return document.chatApplet.getUser(username);
}


ChatServer.prototype.getJavaRoomObject = function (roomname) {
return document.chatApplet.getRoom(roomname);
}


ChatServer.prototype.invite = function (roomName, otherUserName) {
document.chatApplet.invite(otherUserName, roomName);
}


ChatServer.prototype.mute = function (username) {
document.chatApplet.mute(username);
}


ChatServer.prototype.kick = function (username) {
document.chatApplet.kick(username);
}


ChatServer.prototype.ban = function (username, seconds) {
document.chatApplet.ban(username, seconds);
}



ChatServer.prototype.requestSettingChange = function (key, value) {
document.chatApplet.requestSettingChange(key, value);
}
ChatServer.prototype.requestSettingDeletion = function (key) {
document.chatApplet.requestSettingDeletion(key, value);
}




ChatServer.prototype.imAcceptInvitation = function (sendingJavaUserObject, roomName) {
document.chatApplet.imAcceptInvitation(sendingJavaUserObject, roomName);
}

ChatServer.prototype.imDeclineInvitation = function (sendingJavaUserObject, roomName) {
document.chatApplet.imDeclineInvitation(sendingJavaUserObject, roomName);
}







ChatRoom.prototype._id;
ChatRoom.prototype._name = false;
ChatRoom.prototype._javaRoomName = false;
ChatRoom.prototype._groupDesignation;
ChatRoom.prototype._noOfUsers;
ChatRoom.prototype._catIndex;
ChatRoom.prototype._vipOnly = false;
ChatRoom.prototype._javaRoomObject;


function ChatRoom(id, noOfUsers, roomObject) {
this._id = id;
this._noOfUsers = noOfUsers;
this._catIndex = -1;
this._vipOnly = false;
this._javaRoomObject = roomObject;
}


ChatRoom.prototype.getID = function () {
return this._id;
}


ChatRoom.prototype.getName = function () {
if (this._name == false) {

var theRoomHandler = chatController._roomHandler;


var theName = '' + this._javaRoomObject.getName();


this._groupDesignation = theRoomHandler.getGroupNum(theName);


theName = theRoomHandler.removeGroupNum(theName);

this._name = theName;
}
return this._name;
}

ChatRoom.prototype.setName = function (theName) {
this._name = theName;
}


ChatRoom.prototype.toString = function () {

var origRoomName = this.getOrigRoomName();
var numberStarts = origRoomName.indexOf(' - ');

if (numberStarts == -1) {
return 0;
} else {
var string = origRoomName.substr(numberStarts + 3);
return parseInt(string, 10);
}
}


ChatRoom.prototype.getNoOfUsers = function () {
return this._noOfUsers;
}

ChatRoom.prototype.setNoOfUsers = function (noOfUsers) {
this._noOfUsers = noOfUsers;
}


ChatRoom.prototype.getCategoryIndex = function() {
return this._catIndex;
}

ChatRoom.prototype.setCategoryIndex = function(index) {
this._catIndex = index;
}


ChatRoom.prototype.isVIPOnly = function() {
return this._vipOnly;
}


ChatRoom.prototype.getOrigRoomName = function () {


if (this._javaRoomName == false) {
if (this._javaRoomObject) {
this._javaRoomName = this._javaRoomObject.getName();
return this._javaRoomName;
}
} else {
return this._javaRoomName;
}

return this.getName();
}


ChatRoom.prototype.getPrettyName = function (excludeGameName) {

var excludeGameName = (excludeGameName != true ? false : true);
var origRoomName = this.getOrigRoomName();



if (!chatSettings.isMultiplayerChat()) {
var numberStarts = origRoomName.indexOf(' - ');

if (numberStarts == -1) {

var roomNumber = "Rum 1";
var prettyName = (excludeGameName ? roomNumber : origRoomName + ' - ' + roomNumber);

} else {

var roomNumberOnly = "Rum " + origRoomName.substr(numberStarts + 3);
var roomNameOnly = origRoomName.substr(0, numberStarts);

var prettyName = (excludeGameName ? roomNumberOnly : roomNameOnly + ' - ' + roomNumberOnly);
}

} else if (chatSettings.isTournament()) {

var prettyName = "Turneringsbord";

} else {

var firstColonPos = origRoomName.indexOf(':'); 
var searchReg = origRoomName.search('(_)[A-Z]{2}(_)');
var tableName = origRoomName.substr(firstColonPos + 1);

if (searchReg > 0) {
var posReg = searchReg + 4;
if (firstColonPos > 0) {

var prettyName = tableName;

} else {

var prettyName = "Rum " + origRoomName.substr(posReg);

if (!excludeGameName) {
prettyName = origRoomName.substr(0, searchReg) + ' ' + prettyName;
}
}
} else {
var prettyName = origRoomName.substr(0, firstColonPos) + ' ' + tableName;
}


var secondColonPos = prettyName.indexOf(':'); 
if (secondColonPos > 0) {
prettyName = prettyName.substr(0, secondColonPos);
}
}
return prettyName;
}


ChatRoom.prototype.isCurrent = function () {

var currentlyJoinedRoom = chatController._roomHandler.getCurrent();
if (currentlyJoinedRoom != undefined && currentlyJoinedRoom.getId() == this.getID()) {
return true;
}
return false;
}






ChatRoomCategory.prototype._name;
ChatRoomCategory.prototype._rooms;
ChatRoomCategory.prototype._iconHtml = false;
ChatRoomCategory.prototype._defaultRoomName;


function ChatRoomCategory(name) {
this._name = name;
this._rooms = new Array();
}


ChatRoomCategory.prototype.getName = function () {
return this._name;
}


ChatRoomCategory.prototype.toString = function () {
return this._name;
}


ChatRoomCategory.prototype.addRoom = function (chatRoom) {
this._rooms[this._rooms.length] = chatRoom;

if (this._defaultRoomName == undefined) {
this._defaultRoomName = chatRoom.getOrigRoomName();
}
}


ChatRoomCategory.prototype.getDefaultRoomName = function () {
if (this._defaultRoomName != undefined) {
return this._defaultRoomName;
}
return '';
}


ChatRoomCategory.prototype.hasMoreRooms = function () {
return (this._rooms.length > 1);
}


ChatRoomCategory.prototype.holdsCurrentlyJoinedRoom = function () { 

var currentRoom = chatController._roomHandler.getCurrent();
if (currentRoom) {

var currentRoomID = currentRoom.getId();
var theRooms = this._rooms;

var theLength = theRooms.length;
for (var index = 0; index < theLength; index++) {
var room = theRooms[index];
if (room) {
if (room.getID() === currentRoomID) {
return true;
}
}
}
return false;
}
}


ChatRoomCategory.prototype.getIconHtml = function () {
if (this._iconHtml == false) {
this._iconHtml = this._generateIconHtml();
}
return this._iconHtml;
}

ChatRoomCategory.prototype._generateIconHtml = function () {


var imageFilename = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-221px -271px;"></div></div>';
var prettyCatName = '' + this.getName();
var prettyCatName = prettyCatName.replace(' Tournament', '');

var gameIconObject = chatController._roomHandler.getGameIcons();

if (prettyCatName.indexOf('VIP') == -1) {

var funcCall = 'gameIconObject.ChatRoomCategory_' + prettyCatName + ';';
var imageFilename = '' + eval(funcCall);

if (imageFilename == 'undefined') {
var funcCall = 'gameIconObject.ChatRoomCategory_' + prettyCatName.substr(0, prettyCatName.length-1);
imageFilename = '' + eval(funcCall);
}

if (imageFilename == 'undefined') {
imageFilename = '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-201px -271px;"></div></div>';
}
}
return imageFilename;
}


ChatRoomCategory.prototype.getTotalUsersOnline = function () {

var total = 0;
var theRooms = this._rooms;

var theLength = theRooms.length;
for (var index = 0; index < theLength; index++) {
var room = theRooms[index];
if (room) {
total += room.getNoOfUsers();
}
}
return total;
}


ChatRoomCategory.prototype.draw = function () {


var holdsCurrentRoom = this.holdsCurrentlyJoinedRoom();

var currentHeaderClass= (holdsCurrentRoom ? ' toggleBoxHeaderCurrent' : (this.hasMoreRooms() ? '' : ' toggleBoxHeaderOnlyRoom'));
var usercountTextClass= '';
var gameName= (holdsCurrentRoom ? '<strong>' + this.getName() + '</strong>' : this.getName());
var online = this.getTotalUsersOnline();
var toggleboxContent = '';

var defaultRoomName = this.getDefaultRoomName();
var theRooms = this._rooms;

if (this.hasMoreRooms()) {

theRooms.sort(chatTools.compareIntegers);

var stringArray = new Array();

var theLength = theRooms.length;

for (var index = 0; index < theLength; index++) {
var room = theRooms[index];
if (room) {

var onOffIcon = (room.isCurrent() ? '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-261px -271px;"></div></div>' : '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-281px -271px;"></div></div>');
var prettyName = room.getPrettyName(true);
defaultRoomName = room.getOrigRoomName();

stringArray[index] = '<div class="roomRow"><div class="origRoomName">' + defaultRoomName + '</div><div class="glassbar"><div class="glassbarLeftside"></div><div class="glassbarMiddle"></div><div class="glassbarRightside"></div></div><div class="front"><div class="roomIcon">' + onOffIcon + '</div><div class="roomName"><a href="#" class="link11black"><span class="gameName">' + prettyName + '</span></a><span class="noOfChatters ">(' + room.getNoOfUsers() + ')</span></div></div></div>';
}
}
toggleboxContent = '<div class="toggleBoxContent">' + stringArray.join('') + '</div>';

}
return '<div class="toggleBox"><div class="toggleBoxHeader' + currentHeaderClass + '"><div class="origRoomName">' + defaultRoomName + '</div><div class="glassbar"><div class="glassbarLeftside"></div><div class="glassbarMiddle"></div><div class="glassbarRightside"></div></div><div class="front"><div class="gameIcon">' + this.getIconHtml() + '</div><div class="toggleBoxHeaderContent"><span class="gameName">' + gameName + '</span><span class="noOfChatters ' + usercountTextClass + '">(' + online + ')</span></div><div style="clear:both;"></div></div></div>' + toggleboxContent + '</div>';
}




 


ChatRoomHandler.prototype._DEFAULT_BLOCK_TIME = 5;
ChatRoomHandler.prototype._MINIMUM_ROOMS_B4_DRAW = 1;

ChatRoomHandler.prototype._currentJavaRoom = null;
ChatRoomHandler.prototype._currentJavaTableRoom = null;
ChatRoomHandler.prototype._persistentRooms = new Array();
ChatRoomHandler.prototype._privateRooms = new Array();
ChatRoomHandler.prototype._categories = new Array();

ChatRoomHandler.prototype._gameIconsObject = chatVars.gameIconObject;
ChatRoomHandler.prototype._roomlistRedrawBlocked = false;


function ChatRoomHandler() {}


ChatRoomHandler.prototype.getFromID = function (javaRoomObjectID) {

var theRooms = this._persistentRooms;
for (var index in theRooms) {
var room = theRooms[index];

if (javaRoomObjectID == room.getID()) {
return room;
}
}
return false;
}


ChatRoomHandler.prototype.getCurrent = function () {

var defaultRoomName = chatVars.defaultRoomName;


if (typeof(this._currentJavaRoom) != 'object' && defaultRoomName.length) {
this._currentJavaRoom = chatController._server.getJavaRoomObject(defaultRoomName);
}
return this._currentJavaRoom;
}


ChatRoomHandler.prototype.setCurrent = function (javaRoomObject) {
this._currentJavaRoom = javaRoomObject;

}

ChatRoomHandler.prototype.flushCurrent = function () {
this._currentJavaRoom = null;
}




ChatRoomHandler.prototype.getCurrentTableRoom = function () {
return this._currentJavaTableRoom;
}


ChatRoomHandler.prototype.setCurrentTableRoom = function (javaRoomObject) {
this._currentJavaTableRoom = javaRoomObject;
}

ChatRoomHandler.prototype.flushCurrentTableRoom = function () {
this._currentJavaTableRoom = null;
}

ChatRoomHandler.prototype.multiplayerTableRoomJoined = function () {
return (this._currentJavaTableRoom != null);
}




ChatRoomHandler.prototype.getGameIcons = function () {
return this._gameIconsObject;
}


ChatRoomHandler.prototype.getPrettyRoomName = function (javaRoomObject) {

var name = javaRoomObject.getName();

if (this.isPrivate(name) || this.isIMRoom(name)) {
return "privat chat";
}

var dummy = new ChatRoom(-1, 0, javaRoomObject);
return dummy.getPrettyName();
}


ChatRoomHandler.prototype.getGroupNum = function (roomName) {

var groupDesignationStarts = roomName.indexOf('{');
var groupDesignationEnds = roomName.indexOf('}');
if (groupDesignationStarts != -1 && groupDesignationEnds != -1) {

var theGroup = roomName.substring( (groupDesignationStarts + 1), groupDesignationEnds);
return theGroup;
}

return false;
}

ChatRoomHandler.prototype.removeGroupNum = function (string) {
var stripped = string.replace(/^\{\d+\}/, '');
return stripped;
}


ChatRoomHandler.prototype.removeRoomNum = function (string) {
var stripped = string.replace(/ - \d+$/, '');
return stripped;
}


ChatRoomHandler.prototype.getNoOfChatters = function (javaRoomObject) {
return javaRoomObject.getChatters().length;
}


ChatRoomHandler.prototype.isMultiplayerTable = function (javaRoomObject) {

if (javaRoomObject) {
return javaRoomObject.getName().indexOf(":") > -1;
}
return false;
}

ChatRoomHandler.prototype.isMultiplayerTableName = function (roomName) {
if (roomName && roomName.length) {
return roomName.indexOf(":") > -1;
}
return false;
}




ChatRoomHandler.prototype.roomExists = function (roomName) {
if (roomName != undefined) {

var theRooms = this._persistentRooms;
for (var index in theRooms) {

var room = theRooms[index];

if (room.getName() == roomName) {
return true;
}
}
}
return false;
}

ChatRoomHandler.prototype.removeRoom = function (roomName) {
if (roomName != undefined) {

var theRooms = this._persistentRooms;
for (var index in theRooms) {

var room = theRooms[index];

if (room.getName() == roomName) {
this._persistentRooms.splice(index, 1); 
return true;
}
}
}
return false;
}


ChatRoomHandler.prototype.getCurrentlyViewedRoomName = function () {

var chatareaClassname = $('div#chatboxContentWrapper > div.subareaContainer > div.subareaChatTab > div.chatarea:visible').attr('class');
if (chatareaClassname != undefined) {
chatareaClassname = chatareaClassname.split(' ');
chatareaClassname = chatareaClassname[1];
} 

if (chatareaClassname == undefined || chatareaClassname == 'chatareaGeneral') {


var theRoom = this.getCurrentlyViewedRoom();
if (theRoom) {
return theRoom.getName();

} else {

var gameName = chatController.getCurrentGameName();
return gameName;
}

} else {
return chatareaClassname.substr(8);
}
}

ChatRoomHandler.prototype.getCurrentlyViewedRoom = function () {

if (chatSettings.isMultiplayerChat() && chatController._roomHandler.multiplayerTableRoomJoined()) {
var theRoom = this.getCurrentTableRoom();
} else {
var theRoom = this.getCurrent();
}
return theRoom;
}


ChatRoomHandler.prototype.createPrivateRoomName = function (otherUserName) {

var date = new Date();
var unix = Math.floor(date.getTime() / 1000);

var selfObject = chatController._userHandler.getCurrent()._chatUserObject;

return 'priv__' + selfObject.getName() + '__vs__' + otherUserName + '__unix__' + unix;
}


ChatRoomHandler.prototype.createPrivateRoom = function (javaRoomObject) {

var theRoomObject = new ChatRoom(javaRoomObject.getId(), 2, javaRoomObject);
return theRoomObject;
}


ChatRoomHandler.prototype.getPrivateRoom = function (privateRoomName) {


if (privateRoomName != undefined) {

var theRooms = this.getPrivateRooms();
for (var index in theRooms) {
var roomObject = theRooms[index];
var javaRoomObject = roomObject._javaRoomObject;

if (javaRoomObject.getName() == privateRoomName) {
return roomObject;
}
}
return false;
}
}

ChatRoomHandler.prototype.getPrivateRooms = function () {
return this._privateRooms;
}


ChatRoomHandler.prototype.isPrivate = function (roomName) {
return roomName.indexOf('priv__') > -1;
}

ChatRoomHandler.prototype.isIMRoom = function (roomName) {
return roomName.indexOf('IM') > -1;
}


ChatRoomHandler.prototype.isJailRoom = function (roomName) {

if (roomName == undefined || roomName == null) {
var currentRoom = chatController._roomHandler.getCurrent();
if (currentRoom != undefined) {
var roomName = currentRoom.getName();
} else {
return false;
}
}
return roomName.indexOf('PrisonCell') > -1;
}


ChatRoomHandler.prototype.getIconHtml = function(javaRoomObject) {

var catName = this.removeRoomNum(javaRoomObject.getName());
catName = this.removeGroupNum(catName);
 
var dummyCat = new ChatRoomCategory(catName);
return dummyCat.getIconHtml();
}


ChatRoomHandler.prototype.hasPrivateChatWith = function (otherUsername) {

var ownUserName = chatController._userHandler.getCurrent()._chatUserObject.getName();

var option1 = 'priv__' + ownUserName + '__vs__' + otherUsername + '__unix';
var option2 = 'priv__' + otherUsername + '__vs__' + ownUserName + '__unix';

var theRooms = this.getPrivateRooms();
for (var index in theRooms) {
var room = theRooms[index];
var theName = room.getName();

if (theName.indexOf(option1) == 0 || theName.indexOf(option2) == 0) {
return true;
}
}
return false;
}


ChatRoomHandler.prototype.currentChatterIsAlone = function () {

var currentJavaRoomObject = this.getCurrent();
var noOfChatters = 0;

if (currentJavaRoomObject) {
noOfChatters = currentJavaRoomObject.numChatters();
}
return (noOfChatters == 1);
}


ChatRoomHandler.prototype.addPrivateRoom = function (theRoomObject) {
if (!chatTools.inArray(this._privateRooms, theRoomObject)) {
this._privateRooms[this._privateRooms.length] = theRoomObject;
}
}


ChatRoomHandler.prototype.removePrivateRoom = function (theRoomObject) {

var theRooms = this.getPrivateRooms();
for (var index in theRooms) {
var room = theRooms[index];

if (room.getID() == theRoomObject.getID()) {
this._privateRooms.splice(index, 1); 
}
}
}


ChatRoomHandler.prototype._buildCategories = function () {


var theRooms = this._persistentRooms;
var theCats = this._categories;

for (var index in theRooms) {
var room = theRooms[index];


 var catName = this.removeRoomNum(room.getName());
catName = this.removeGroupNum(catName);

 if (catName != '') {

 
 var catIndex = -1;
 for (var index in theCats) {
 if (theCats[index].getName() == catName) {
 catIndex = index;
 }
 }

 
 if (catIndex == -1) {
 catIndex = theCats.length;
 theCats[catIndex] = new ChatRoomCategory(catName);
 }

 
 room.setCategoryIndex(catIndex);
 theCats[catIndex].addRoom(room);
 }
}


theCats.sort(chatTools.compareStrings);

this._categories = theCats;
return theCats;
}

ChatRoomHandler.prototype.getCategories = function () {
if (this._categories.length == 0) {
this._buildCategories();
}
return this._categories;
}


ChatRoomHandler.prototype.drawAllActive = function () {

var html = new Array();
var cats = this.getCategories();

for (var index in cats) {
var cat = cats[index];

if (cat.getName().indexOf('LoggedOutOfChat') == 0 || cat.getName().indexOf('ChatDev') == 0) {
continue;
}
if (cat.getName().indexOf('PrisonCell') == 0) {
continue;
}
html[index] = cat.draw();
}
html[++index] = '<div id="roomsWaitBar" class="subarea" style="display:none;"><div class="waitbar"><img src="http://www.komogvind.dk/images/progressing.gif" width="86" height="16" alt="progressbar"></div></div>';

return html.join('');
}


ChatRoomHandler.prototype.drawTableRoomRows = function () {

var lobbyJavaRoomObject = this.getCurrent();
var theCategory = new ChatRoomCategory(lobbyJavaRoomObject.getName());

theCategory.addRoom(new ChatRoom(lobbyJavaRoomObject.getID(), lobbyJavaRoomObject.numChatters(), lobbyJavaRoomObject));

for (var index = 1; index < 5; index++ ) {

var theRoom = new ChatRoom(index, 0, lobbyJavaRoomObject);
theRoom.setName('BingoStars_DK_1:Bord 14');
theCategory.addRoom(theRoom);
}

return theCategory.draw() + '<div id="roomsWaitBar" class="subarea" style="display:none;"><div class="waitbar"><img src="http://www.komogvind.dk/images/progressing.gif" width="86" height="16" alt="progressbar"></div></div>';
}




ChatRoomHandler.prototype.replacePersistentRoom = function (javaRoomObject, noOfChatters) {

var theRoomID = javaRoomObject.getId();
var wasInArray = false;


for (var index in this._persistentRooms) {

var existingRoom = this._persistentRooms[index];
if (existingRoom.getID() == theRoomID) {


existingRoom.setNoOfUsers(noOfChatters);
wasInArray = true;
break;
}
}

if (!wasInArray ) {

var theRoomObject = new ChatRoom(theRoomID, noOfChatters, javaRoomObject);
this._persistentRooms[this._persistentRooms.length] = theRoomObject;
}
}




ChatRoomHandler.prototype.minimumRoomsRetrieved = function () {
return (this._persistentRooms.length >= this._MINIMUM_ROOMS_B4_DRAW);
}


ChatRoomHandler.prototype.roomlistRedrawBlocked = function() {
return (this._roomlistRedrawBlocked != false);
}


ChatRoomHandler.prototype.blockRoomlistRedraw = function(howManySecs) {

this._roomlistRedrawBlocked = true;

howManySecs = (undefined == howManySecs ? this._DEFAULT_BLOCK_TIME : howManySecs);
howManySecs = howManySecs * 1000;

globalRoomHandlerCopy = this;
window.setTimeout('globalRoomHandlerCopy.unblockRoomlistRedraw();', howManySecs);
}


ChatRoomHandler.prototype.unblockRoomlistRedraw = function() {
this._roomlistRedrawBlocked = false;
}



 




ChatUser.prototype._javaUserObject = null;

ChatUser.prototype._ID = null;
ChatUser.prototype._name = null;
ChatUser.prototype._properties = null;
ChatUser.prototype._isBanAdm = null;
ChatUser.prototype._isFemale = null;
ChatUser.prototype._isMale = null;
ChatUser.prototype._isMuteAdm = null;
ChatUser.prototype._isKickAdm = null;
ChatUser.prototype._isMuted = null;
ChatUser.prototype._isStaff = null;
ChatUser.prototype._isStealth = null;
ChatUser.prototype._isVip = null;
ChatUser.prototype._isVisibleAdm = null;

ChatUser.prototype._usersRowHtml = null;
ChatUser.prototype._gameRating = null;
ChatUser.prototype._ratingIcon = null;

ChatUser.prototype._chosenChatIconID= null;

function ChatUser (javaUserObject) {
this._javaUserObject = javaUserObject;
}


ChatUser.prototype.getID = function () {
if (this._ID == null && this._javaUserObject) {
this._ID = this._javaUserObject.getId();
}
return this._ID;
}
ChatUser.prototype.getName = function () {
if (this._name == null && this._javaUserObject) {
this._name = this._javaUserObject.getName();
}
return this._name;
}
ChatUser.prototype.getProperties = function () {
if (this._properties == null && this._javaUserObject) {
this._properties = this._javaUserObject.getProperties();
}
return this._properties;
}
ChatUser.prototype.isBanAdm = function () {
if (this._isBanAdm == null && this._javaUserObject) {
this._isBanAdm = this._javaUserObject.isBanAdm();
}
return this._isBanAdm;
}
ChatUser.prototype.isFemale = function () {
if (this._isFemale == null && this._javaUserObject) {
this._isFemale = this._javaUserObject.isFemale();
}
return this._isFemale;
}
ChatUser.prototype.isMale = function () {
if (this._isMale == null && this._javaUserObject) {
this._isMale = this._javaUserObject.isMale();
}
return this._isMale;
}
ChatUser.prototype.isMuteAdm = function () {
if (this._isMuteAdm == null && this._javaUserObject) {
this._isMuteAdm = this._javaUserObject.isMuteAdm();
}
return this._isMuteAdm;
}
ChatUser.prototype.isKickAdm = function () {
if (this._isKickAdm == null && this._javaUserObject) {
this._isKickAdm = this._javaUserObject.isKickAdm();
}
return this._isKickAdm;
}
ChatUser.prototype.isMuted = function () {
if (this._isMuted == null && this._javaUserObject) {
this._isMuted = this._javaUserObject.isMuted();
}
return this._isMuted;
}
ChatUser.prototype.isStaff = function () {
if (this._isStaff == null && this._javaUserObject) {
this._isStaff = this._javaUserObject.isStaff();
}
return this._isStaff;
}
ChatUser.prototype.isStealth = function () {
if (this._isStealth == null && this._javaUserObject) {
this._isStealth = this._javaUserObject.isStealth();
}
return this._isStealth;
}
ChatUser.prototype.isVip = function () {
if (this._isVip == null && this._javaUserObject) {
this._isVip = this._javaUserObject.isVip();
}
return this._isVip;
}
ChatUser.prototype.isVisibleAdm = function () {
if (this._isVisibleAdm == null && this._javaUserObject) {
this._isVisibleAdm = this._javaUserObject.isVisibleAdm();
}
return this._isVisibleAdm;
}
ChatUser.prototype.getLinkClass = function () {
return (this.isMale() ? 'size11profileblue' : 'size11profilered');
}


ChatUser.prototype.drawUsersRow = function (smallText) {

if (this._usersRowHtml == null) {

var chatIconHtml = chatController._userHandler.getChatIconHtml(this._javaUserObject);

var rightElem = '';


if (smallText != undefined) {

rightElem = '<div class="miscText size10grey">' + smallText + '</div>';


} else if (chatSettings.isMultiplayerChat() && chatController._roomHandler.multiplayerTableRoomJoined()) {

var rating = this.getRating();
if (rating) {
var image =  '<img class="ratingIcon"  src="../../images/rating/rate_' + this.getRatingIcon(rating) + '.gif" alt="" />';
rightElem = '<div class="miscText size11grey"><strong>' + rating + '</strong>' + image + '</div>';
}
}
this._usersRowHtml = '<div class="userRow"><div class="userIcon">' + chatIconHtml + ' </div><div class="userName ' + this.getLinkClass() + '"><strong>' + this.getName() + '</strong></div>' + rightElem + '</div>';
}
return this._usersRowHtml;
}


ChatUser.prototype.getRating = function () {
if (this._gameRating == null) {

var cachedChatController = chatController;

var arrayIndex = this.getID();
var chatProfileInfoUser = cachedChatController._userHandler.getProfileInfoUser(arrayIndex);

if (typeof(chatProfileInfoUser) == 'object') {

this._gameRating = chatProfileInfoUser.getProfileInfoRating();

} else if (cachedChatController._roomHandler.multiplayerTableRoomJoined()){

cachedChatController._userHandler.requestUserInfo(this.getName());
}
}
return (this._gameRating != null ? this._gameRating : false);
}

ChatUser.prototype.getRatingIcon = function (rating) {

if (this._ratingIcon == null) {

var ratingpic = '';

if (rating == 'top3') {
ratingpic = '17';
} else if (rating == 'top2') {
ratingpic = '18';
} else if (rating == 'top1') {
ratingpic = '19';
} else if (rating == 0) {
ratingpic = '0';
} else if (rating < 200) {
ratingpic = '0';
} else if (rating <=500) {
ratingpic = '1';
} else if (rating <= 800) {
ratingpic = '2';
} else if (rating <= 1100) {
ratingpic = '3';
} else if (rating <= 1400) {
ratingpic = '4';
} else if (rating <= 1800) {
ratingpic = '5';
} else if (rating <= 2200) {
ratingpic = '6';
} else if (rating <= 2500) {
ratingpic = '7';
} else if (rating <= 2800) {
ratingpic = '8';
} else if (rating <= 3100) {
ratingpic = '9';
} else if (rating <= 3400) {
ratingpic = '10';
} else if (rating <= 3700) {
ratingpic = '11';
} else if (rating <= 4000) {
ratingpic = '12';
} else if (rating <= 4300) {
ratingpic = '13';
} else if (rating <= 4600) {
ratingpic = '14';
} else if (rating <= 4900) {
ratingpic = '15';
} else if (rating <= 5200) {
ratingpic = '16';
} else if (rating > 5200) {
ratingpic = '16';
}
this._ratingIcon = ratingpic;
}
return this._ratingIcon;
}

ChatUser.prototype.toString = function () {
return this.getName();
}



 

ChatUserSelf.prototype._friendsArray = chatVars.friendsArray;
ChatUserSelf.prototype._ignoreArray = chatVars.ignoreArray;
ChatUserSelf.prototype._chatUserObject;

ChatUserSelf.prototype._isJailInmate;


function ChatUserSelf(javaUserObject) {
this._chatUserObject = new ChatUser(javaUserObject);

this._isJailInmate = chatVars.selfIsInmate;
}


ChatUserSelf.prototype.hasFriends = function () {
return (this._friendsArray.length > 0);
}


ChatUserSelf.prototype.hasAsFriend = function (userObject) {

if (typeof(userObject) == 'object') {
if (chatTools.inArray(this._friendsArray, userObject.getName())) {
return true;
}
}
return false;
}


ChatUserSelf.prototype.ignoresUser = function (senderUserName) {
if (chatTools.inArray(this._ignoreArray, senderUserName)) {
return true;
}
return false;
}


ChatUserSelf.prototype.ignore = function (targetJavaUserObject) {

if (typeof(targetJavaUserObject) == 'object') {
var username = targetJavaUserObject.getName();

if (!chatTools.inArray(this._ignoreArray, username)) {
this._ignoreArray[this._ignoreArray.length] = username;
}
}
}


ChatUserSelf.prototype.incarcerate = function () {
this._isJailInmate = true;
}

ChatUserSelf.prototype.releaseFromJail = function () {
this._isJailInmate = false;
}

ChatUserSelf.prototype.isInJail = function () {
return this._isJailInmate;
}



 

ChatProfileInfoUser.prototype._chatUserProfileObject = null;
ChatProfileInfoUser.prototype._isMale = null;
ChatProfileInfoUser.prototype._rating = null;
ChatProfileInfoUser.prototype._tokens = null;

ChatProfileInfoUser.prototype._profileObjectName = null;
ChatProfileInfoUser.prototype._profileObjectId = null;



function ChatProfileInfoUser(javaUserProfileObject) {
this._chatUserProfileObject = javaUserProfileObject;
}

ChatProfileInfoUser.prototype.getProfileObjectName = function() {
if (this._profileObjectName == null && this._chatUserProfileObject) {
this._profileObjectName = this._chatUserProfileObject.getName();
}
return this._profileObjectName;
}

ChatProfileInfoUser.prototype.getProfileObjectId = function() {
if (this._profileObjectId == null && this._chatUserProfileObject) {
this._profileObjectId = this._chatUserProfileObject.getId();
}
return this._profileObjectId;
}



ChatProfileInfoUser.prototype.isMale = function () {
if (this.isMale == null) {
var funco = chatVars.funcIsMale;
this._isMale = eval('this._chatUserProfileObject.' + funco + '()');
}
return this._isMale;
}
ChatProfileInfoUser.prototype.getProfileInfoRating  = function () {
if (this._rating == null) {
var funco = chatVars.funcGetRating;
this._rating = eval('this._chatUserProfileObject.' + funco + '()');
}
return this._rating;
};
ChatProfileInfoUser.prototype.tokens = function () {
if (this._tokens == null) {
var funco = chatVars.funcGetTokens;
this._tokens = eval('this._chatUserProfileObject.' + funco + '()');
}
return this._tokens;
};



 

ChatUserHandler.prototype._DEFAULT_BLOCK_TIME = 5;


ChatUserHandler.prototype._currentUser;
ChatUserHandler.prototype._currentChatters = new Array();
ChatUserHandler.prototype._currentTableChatters = new Array();
ChatUserHandler.prototype._currentChatterUsernames = null;
ChatUserHandler.prototype._profileInfoUserObjects = new Array();
ChatUserHandler.prototype._userlistRedrawBlocked = false;
ChatUserHandler.prototype._profileInfoRedrawBlocked = false;

ChatUserHandler.prototype._nongameProfileInfoObjects = new Array();


function ChatUserHandler() {}


ChatUserHandler.prototype.setCurrent = function (javaUserObject) {
if (javaUserObject) {
this._currentUser = new ChatUserSelf(javaUserObject);
return this._currentUser;
}
return false;
}


ChatUserHandler.prototype.getCurrent = function () {
return this._currentUser;
}


ChatUserHandler.prototype.allowMessagesFrom = function(javaSenderUserObject) {

if (chatSettings.chattingAllowed()) {

if (this._currentUser) {
return !this._currentUser.ignoresUser(javaSenderUserObject.getName());
}
}
return false;
};


ChatUserHandler.prototype.getProfileInfoUser = function (chatUserObjectId) {


var list = this._profileInfoUserObjects;
var candidate = list[chatUserObjectId];

if (candidate && candidate._chatUserProfileObject) {

var candidateId = candidate.getProfileObjectId();
if (candidateId == chatUserObjectId) {
return candidate;
}
}
return false;
}


ChatUserHandler.prototype.getNongameProfileInfo = function (username) {


var list = this._nongameProfileInfoObjects;

for (var index in list) {
var candidate = list[index];
if (candidate) {

if (candidate.username == username) {
return candidate;
}
}
}
return false;
}


ChatUserHandler.prototype.cacheNongameProfileInfoObject = function (profileInfoObject) {
var newIndex = this._nongameProfileInfoObjects.length;
this._nongameProfileInfoObjects[newIndex] = profileInfoObject;
}

 
ChatUserHandler.prototype.uncacheNongameProfileInfoObject = function (username) {


var list = this._nongameProfileInfoObjects;

for (var index in list) {
var candidate = list[index];
if (candidate) {

if (candidate.username == username) {
break;
}
}
}


this._nongameProfileInfoObjects.splice(index, 1);
}


ChatUserHandler.prototype.getChatIconHtml = function (javaUserObject) {

if (chatController._roomHandler.isJailRoom()) {
return '<div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-221px -415px;"></div></div>';

}
var existingChatIconID = this.getChatIconID(javaUserObject);
return chatController._box.getCachedChatIconHtml(existingChatIconID);
}




ChatUserHandler.prototype.getChatIconID = function (javaUserObject) {

var chosenOne = javaUserObject.getSettings().get('chosenChatIconID');
if (chosenOne) {

if (chosenOne !== 'chatIconX1Y26' && chosenOne !== 'chatIconX2Y26') {
return chosenOne;

} else if (javaUserObject.isBanAdm()) {
return chosenOne;
}
}

if (javaUserObject.isVip()) {
var existingChatIconID = (javaUserObject.isMale() ? 'chatIconX14Y22' : 'chatIconX15Y22');
} else {
var existingChatIconID = (javaUserObject.isMale() ? 'chatIconX12Y22' : 'chatIconX13Y22');
}
return existingChatIconID;
}


ChatUserHandler.prototype.resetCurrentChatters = function () {
this._currentChatters = new Array();
}

ChatUserHandler.prototype.resetCurrentTableChatters = function () {
this._currentTableChatters = new Array();
}




ChatUserHandler.prototype.populateChatters = function () {

var drawMultiplayerTableVersion = (chatSettings.isMultiplayerChat() && chatController._roomHandler.multiplayerTableRoomJoined());


if (drawMultiplayerTableVersion) {

if (this._currentTableChatters.length == 0){
this._populateCurrentTableChatters();
}
return this._currentTableChatters;
 
} else {

if (this._currentChatters.length == 0){
this._populateCurrentChatters();
}
return this._currentChatters;
}
}


ChatUserHandler.prototype.getFriends = function (chatUserObject, theChatters) {

var usersFriends = new Array();

for (var index in theChatters) {

var possibleFriend = theChatters[index];

if (chatUserObject.hasAsFriend(possibleFriend)) {
usersFriends.push(possibleFriend);
}
}
return usersFriends;
}


ChatUserHandler.prototype.drawCurrentChatters = function () {

var htmlAr = new Array();
var theRoomHandler = chatController._roomHandler;
var drawMultiplayerTableVersion = (chatSettings.isMultiplayerChat() && theRoomHandler.multiplayerTableRoomJoined());

var theChatters = this.populateChatters();
var userHtml = '';


if (theChatters.length > 0) {

var ownUser = this.getCurrent();

if (drawMultiplayerTableVersion) {
var currentJavaRoom = theRoomHandler.getCurrentTableRoom();
} else {
var currentJavaRoom = theRoomHandler.getCurrent();
}

if (currentJavaRoom) {

var currentRoomName = theRoomHandler.getPrettyRoomName(currentJavaRoom);
var currentRoomUsersNum = theChatters.length;

var currentAdminsNum = 0;
var currentFriendsNum = 0;
var everyoneNum = 0;


theChatters.sort(chatTools.compareStrings);


var allStringArray = new Array();
var friendsStringArray = new Array();
var adminsStringArray = new Array();

for (var index in theChatters) {
var user = theChatters[index];

if (user.isBanAdm() && user.isVisibleAdm()) {

userHtml = user.drawUsersRow(currentRoomName);
adminsStringArray[adminsStringArray.length] = userHtml;
currentAdminsNum++;

} else if (ownUser.hasAsFriend(user)) {

userHtml = user.drawUsersRow(currentRoomName);
friendsStringArray[friendsStringArray.length] = userHtml;
currentFriendsNum++;

} else {
userHtml = user.drawUsersRow();
allStringArray[allStringArray.length] = userHtml;
everyoneNum++;
}
}

currentRoomUsersNum = (currentRoomUsersNum - currentFriendsNum - currentAdminsNum);


if (currentAdminsNum > 0) {
htmlAr[0] = '<div class="toggleBox"><div class="toggleBoxHeader"><div class="plusminusbox icon_plus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-341px -271px;"></div></div></div><div class="plusminusbox icon_minus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-361px -271px;"></div></div></div><div class="toggleBoxHeaderContent"><strong>' + "Admins" + '</strong>&nbsp;<span class="size12grey"><strong>(' + currentAdminsNum + ')</strong></span></div><div style="clear:both;"></div></div><div class="toggleBoxContent"> ' + adminsStringArray.join('') + ' <div style="clear:both;"></div></div></div>';
}


if (currentFriendsNum > 0) {
htmlAr[1] = '<div class="toggleBox"><div class="toggleBoxHeader"><div class="plusminusbox icon_plus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-341px -271px;"></div></div></div><div class="plusminusbox icon_minus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-361px -271px;"></div></div></div><div class="toggleBoxHeaderContent"><strong>' + "Venner" + '</strong>&nbsp;<span class="size12grey"><strong>(' + currentFriendsNum + ')</strong></span></div><div style="clear:both;"></div></div><div class="toggleBoxContent"> ' + friendsStringArray.join('') + ' <div style="clear:both;"></div></div></div>';
}


if (everyoneNum > 0) {
htmlAr[2] = '<div class="toggleBox"><div class="toggleBoxHeader"><div class="plusminusbox icon_plus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-341px -271px;"></div></div></div><div class="plusminusbox icon_minus"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-361px -271px;"></div></div></div><div class="toggleBoxHeaderContent"><strong>' + currentRoomName + '</strong>&nbsp;<span class="size12grey"><strong>(' + currentRoomUsersNum + ')</strong></span></div><div style="clear:both;"></div></div><div class="toggleBoxContent"> ' + allStringArray.join('') + ' <div style="clear:both;"></div></div></div>';
}

htmlAr[3] = '<div id="usersWaitBar" class="subarea" style="display:none;"><div class="waitbar"><img src="http://www.komogvind.dk/images/progressing.gif" width="86" height="16" alt="progressbar"></div></div>';
}
}
return htmlAr.join('');
}


ChatUserHandler.prototype.drawCurrentTableChatters = function () {


if (this._currentTableChatters.length == 0) {
this._populateCurrentTableChatters();
}

var html = '';
var userHtml = '';
var cachedController = this;

var theChatters = this._currentTableChatters;
if (theChatters.length > 0) {

var ownUser = false;
var ownUsername = this.getCurrent()._chatUserObject.getName();


theChatters.sort(chatTools.compareStrings);

if (theChatters.length > 0) {

var currentJavaRoom = chatController._roomHandler.getCurrentTableRoom();
if (currentJavaRoom) {

var currentRoomName = chatController._roomHandler.getPrettyRoomName(currentJavaRoom);
var currentRoomUsersNum = theChatters.length;


var rowsStringArray = new Array();
for (var index in theChatters) {
var user = theChatters[index];

if (ownUsername != user.getName()) {
userHtml = user.drawUsersRow();
rowsStringArray[index] = userHtml;
} else {
ownUser = user;
}
}


if (ownUser && ownUser.drawUsersRow) {
rowsStringArray.unshift(ownUser.drawUsersRow());
}

html = '<div class="tableUsersHeader"><strong>' + currentRoomName + '</strong> <span class="size11lightgrey">(' + currentRoomUsersNum + ' spillere)</span></div>' + rowsStringArray.join('') + ' <div style="clear:both;"></div>';
}
}
}
return html;
}


ChatUserHandler.prototype.repopulateCurrentChatters = function () {
this._currentChatters = new Array();
this._populateCurrentChatters();
}


ChatUserHandler.prototype.getChatter = function (userName) {
var found = false;

if (this._currentChatters.length == 0) {
this.repopulateCurrentChatters();
}

var searchList = this._currentChatters;
for (var index in searchList) {
var user = searchList[index];

if (userName == user.getName()) {
found = user;
break;
}
}

if (!found && chatController._roomHandler.multiplayerTableRoomJoined()) {

if (this._currentTableChatters.length == 0) {
this.repopulateCurrentTableChatters();
}

searchList = this._currentTableChatters;
for (var index in searchList) {
var user = searchList[index];

if (userName == user.getName()) {
found = user;
break;
}
}
}
return found;
}

ChatUserHandler.prototype.addChatter = function (javaUserObject) {

if (this._currentChatters.length != 0 && javaUserObject) {

var theName = javaUserObject.getName();

for (var chatterIndex in this._currentChatters) {
var user = this._currentChatters[chatterIndex];

if (theName == user.getName()) {
break;
}
}

var chatUserObject = new ChatUser(javaUserObject);
this._currentChatters.splice(chatterIndex, 0, chatUserObject);
}
}

ChatUserHandler.prototype.removeChatter = function (javaUserObject) {

if (this._currentChatters.length != 0 && javaUserObject) {

var theName = javaUserObject.getName();

for (var chatterIndex in this._currentChatters) {
var user = this._currentChatters[chatterIndex];

if (theName == user.getName()) {
break;
}
}
this._currentChatters.splice(chatterIndex, 1);
}
}

ChatUserHandler.prototype.replaceChatter = function (javaUserObject) {

if (this._currentChatters.length != 0 && javaUserObject) {

var theName = javaUserObject.getName();

for (var chatterIndex in this._currentChatters) {
var user = this._currentChatters[chatterIndex];

if (theName == user.getName()) {
break;
}
}
var chatUserObject = new ChatUser(javaUserObject);
this._currentChatters.splice(chatterIndex, 1, chatUserObject);
}
}


ChatUserHandler.prototype.getNumTableChatters = function () {
return this._currentTableChatters.length;
}


ChatUserHandler.prototype.repopulateCurrentTableChatters = function () {
this._currentTableChatters = new Array();
this._populateCurrentTableChatters();
}




ChatUserHandler.prototype._populateCurrentChatters = function () {

var theController = chatController;
var javaRoomObject = theController._roomHandler.getCurrent();



if (javaRoomObject) {

var javaUsersList = theController._server.getUsersInRoom(javaRoomObject.getName());
if (javaUsersList != null) {

this._currentTableChatters = new Array();

var javaUsersListSize = javaUsersList.getSize();
for (var index = 0 ; index < javaUsersListSize ; index++) {
var javaUserObject = javaUsersList.get(index);
var chatUserObject = new ChatUser(javaUserObject);
if (chatUserObject) {

this._currentChatters[index] = chatUserObject;
}
}
}
}
}


ChatUserHandler.prototype._populateCurrentTableChatters = function () {

var cachedController = chatController;

var javaRoomObject = cachedController._roomHandler.getCurrentTableRoom();
var multiplayerTableJoined = (chatSettings.isMultiplayerChat() && cachedController._roomHandler.multiplayerTableRoomJoined());

if (javaRoomObject != null && multiplayerTableJoined) {

try {

this._currentTableChatters = new Array();

var numAtTable = javaRoomObject.numChatters();
for (var index = 0; index < numAtTable; index++) {
var javaUserObject = javaRoomObject.getChatterAtIndex(index);

if (javaUserObject) {

var chatUserObject = new ChatUser(javaUserObject);

this._currentTableChatters[index] = chatUserObject;


var arrayIndex = chatUserObject.getID();
if (this.getProfileInfoUser(arrayIndex) == false) {


var username = chatUserObject.getName();
this.requestUserInfo(username);
}
}
}

} catch(e) {
cachedController._sendError('Exception77: - ChatUserHandler._populateCurrentTableChatters - error name:' + e.name + ',  error message: ' + e.message + ' Room name: ' + javaRoomObject.getName());
}
}
}

ChatUserHandler.prototype.flushAllChatters = function () {
this._currentChatters = new Array();
this._currentTableChatters = new Array();
}

ChatUserHandler.prototype.requestUserInfo = function (username) {
if (document.gameObject) {
eval('document.gameObject.' + chatVars.funcRequestUser + '("' + username + '");');
}
}




ChatUserHandler.prototype.isTabUserListEmpty = function () {
return (this._currentChatterUsernames == null || this._currentChatterUsernames.length == 0);
}


ChatUserHandler.prototype.getTabUserList = function () {
return this._currentChatterUsernames;
}

ChatUserHandler.prototype.flushTabUserList = function () {
this._currentChatterUsernames = null;
}


ChatUserHandler.prototype.buildTabUserList = function (partialUsername) {

var currentChatterUsernames = new Array();
var currentRoom = chatController._roomHandler.getCurrentlyViewedRoom();
var chattersJavaObject = currentRoom.getChattersStartingWith(partialUsername);

var index = 0;
for (index ; index < chattersJavaObject.getSize() ; index++) {
currentChatterUsernames[index] = chattersJavaObject.getAlphabetically(index).getName();
}

this._currentChatterUsernames = currentChatterUsernames;
}




ChatUserHandler.prototype._currentTableEmpty = function () {
return this._currentTableChatters.length == 0;
}




ChatUserHandler.prototype.addProfileInfoUser = function (chatProfileInfoUser) {
if (chatProfileInfoUser) {
var newIndex = chatProfileInfoUser.getProfileObjectId();
this._profileInfoUserObjects[newIndex] = chatProfileInfoUser;
}
}




ChatUserHandler.prototype.getLinkClassFromGender = function (isMale) {
return (isMale ?  'size11profileblue' : 'size11profilered');
}




ChatUserHandler.prototype.userlistRedrawBlocked = function() {
return (this._userlistRedrawBlocked != false);
}


ChatUserHandler.prototype.blockUserlistRedraw = function(howManySecs) {

this._userlistRedrawBlocked = true;

howManySecs = (undefined == howManySecs ? this._DEFAULT_BLOCK_TIME : howManySecs);
howManySecs = howManySecs * 1000;

globalUserHandlerCopy = this;
window.setTimeout('globalUserHandlerCopy.unblockUserlistRedraw();', howManySecs);
}


ChatUserHandler.prototype.unblockUserlistRedraw = function() {
this._userlistRedrawBlocked = false;
}




ChatUserHandler.prototype.profileInfoRedrawBlocked = function() {
return (this._profileInfoRedrawBlocked != false);
}


ChatUserHandler.prototype.blockProfileInfoRedraw = function(howManySecs) {

this._profileInfoRedrawBlocked = true;

howManySecs = (undefined == howManySecs ? this._DEFAULT_BLOCK_TIME : howManySecs);
howManySecs = howManySecs * 1000;

globalUserHandlerCopy = this;
window.setTimeout('globalUserHandlerCopy.unblockProfileInfoRedraw();', howManySecs);
}


ChatUserHandler.prototype.unblockProfileInfoRedraw = function() {
this._profileInfoRedrawBlocked = false;
}






ChatSmiley.prototype._chars;
ChatSmiley.prototype._dir;
ChatSmiley.prototype._filename;
ChatSmiley.prototype._imageObject;
ChatSmiley.prototype._vipOnly;
ChatSmiley.prototype._nickname;
ChatSmiley.prototype._html;


function ChatSmiley(typeSetting, chars, filename, vipOnly, nickname) {
this._chars = chars;
this._encodedChars = chatTools._encodeString(this._chars);

this._dir = ((typeSetting == 'static' && filename.indexOf('stu_') == -1) ? 'static' : 'animated');
this._filename = filename;
this._vipOnly = vipOnly;
this._nickname = nickname;

this.remakePublicHtml();
}


ChatSmiley.prototype.getDir = function () {
return this._dir;
}

ChatSmiley.prototype.getChars = function () {
return this._chars;
}

ChatSmiley.prototype.getEncodedChars = function () {
return this._encodedChars;
}

ChatSmiley.prototype.getNickname = function () {
return this._nickname;
}

ChatSmiley.prototype.isVIPOnly = function() {
return this._vipOnly;
}


ChatSmiley.prototype.getFilename = function (greyVersion) {

if (greyVersion) {


var greyFilename = this._filename.replace('.gif', '_grey.gif');
return greyFilename;
}
return this._filename;
}


ChatSmiley.prototype.remakePublicHtml = function (typeSetting) {

this._dir = ((typeSetting == 'static' && this.getFilename().indexOf('stu_') == -1) ? 'static' : 'animated');

var smileyStrAr = new Array('<img src="http://www.komogvind.dk/images/smileys/', this.getDir(), '/', this.getFilename(), '" alt="smiley" align="absmiddle" />');
this._html = smileyStrAr.join('');
}
ChatSmiley.prototype.getHtml = function () {
return this._html;
}








ChatSmileyHandler.prototype._smileys = new Array();
ChatSmileyHandler.prototype._smileyCounter = 100;




ChatSmileyHandler.prototype.drawStuffBoxes = function () {
return this.smileyBoxesGenerator('stuff');
}


ChatSmileyHandler.prototype.drawSmileyBoxes = function () {
return this.smileyBoxesGenerator('smiley');
}


ChatSmileyHandler.prototype.remakeSmileyHtml = function (typeSetting) {
var smileys = this.getAllSmileys();
if (smileys != false) {

for (var nickname in smileys) {
var theSmiley = this.getSmiley(nickname);
theSmiley.remakePublicHtml(typeSetting);
}
}
}


ChatSmileyHandler.prototype.smileyBoxesGenerator = function (category) {

var cachedController = chatController;
var ownUserObject = cachedController._userHandler.getCurrent()._chatUserObject;
var type = chatSettings.getSmileyType();

var categoryWord = (category == 'stuff' ? 'stuff' : 'smiley');

var pageHtml = '';

var stringArray = new Array();

var smileys = this.getAllSmileys();
for (var nickname in smileys) {

var smileyObject = this.getSmiley(nickname);
if (smileyObject != false) {

var greyVersion = false;
if (smileyObject.isVIPOnly() && !ownUserObject.isVip()) {
greyVersion = true;
}

var smileyFilename = smileyObject.getFilename(greyVersion);
if (smileyFilename.indexOf(categoryWord) == 0) {

var smileyDir = smileyObject.getDir();
var smileyNickname = smileyObject.getNickname();
stringArray[stringArray.length] = '<img alt="' + smileyNickname + '" class="smiley" src="http://www.komogvind.dk/images/smileys/' + smileyDir + '/' + smileyFilename + '" />';
}
}
}

stringArray[++stringArray.length] = '<div style="clear:both"></div>';
return stringArray.join('');
}


ChatSmileyHandler.prototype.getSmileyClicked = function (nickname) {
return this.getSmiley(nickname);
}


ChatSmileyHandler.prototype._addSmiley = function (typeSetting, chars, filename, vipOnly, nickname) {

var nickname = '¿' + this._smileyCounter++;
this._smileys[nickname] = new ChatSmiley(typeSetting, chars, filename, vipOnly, nickname);
}

ChatSmileyHandler.prototype.getSmiley = function (nickname) {
return this._smileys[nickname];
}

ChatSmileyHandler.prototype.getAllSmileys = function () {
return this._smileys;
}



ChatSmileyHandler.prototype.swapSmileyPlaceholders = function (theMessage, backToSmileyChars) {

if (backToSmileyChars) {

var typeSetting = chatSettings.getSmileyType();

var smileyPositions = theMessage.split('¿');
var length = smileyPositions.length;
for (var index = 0 ; index < length ; index++) {


var chunk = smileyPositions[index];
if (index > 0) {

var smileyNickname =  '¿' + chunk.substr(0, 3);
var smiley = this.getSmiley(smileyNickname);

if (smiley != undefined) {
var smileyHtml = (typeSetting == 'text' ? smiley.getChars() : smiley.getHtml());
smileyPositions[index] = smileyHtml + chunk.substr(3);
}
}
}
theMessage = smileyPositions.join('');



} else {



var selfIsVip = chatVars.selfIsVip;
var maxSmileyCap = 5;
var maxSmileyCount = 0;

var smileys = this.getAllSmileys();
for (var nickname in smileys) {

var theSmiley = this.getSmiley(nickname);

if (theSmiley.isVIPOnly() && !selfIsVip) {
continue;
} else {

var smileyChars = theSmiley.getChars();
var changedMessage = theMessage;

while (changedMessage.indexOf(smileyChars) != -1) {

if (maxSmileyCount >= maxSmileyCap) {

changedMessage = changedMessage.replace(smileyChars, '');
theMessage = changedMessage;

} else {

changedMessage = changedMessage.replace(smileyChars, theSmiley.getNickname());

if (changedMessage != theMessage) {
maxSmileyCount++;
theMessage = changedMessage;
}
}
}
}
}
}
return theMessage;
}




function ChatSmileyHandler() {

var typeSetting = chatSettings.getSmileyType();

this._addSmiley(typeSetting,':-)','smiley_smile_ani.gif', false, 'Smiling');

this._addSmiley(typeSetting,':-D','smiley_bigsmile_ani.gif',false, 'Smiling big');
this._addSmiley(typeSetting,':-O','smiley_frightened_ani.gif',false, 'Frightened');
this._addSmiley(typeSetting,':-P','smiley_tongue_ani.gif',false, 'Tongue');
this._addSmiley(typeSetting,';-)','smiley_wink_ani.gif',false, 'Winking');
this._addSmiley(typeSetting,':-(','smiley_unhappy_ani.gif',false, 'Unhappy');
this._addSmiley(typeSetting,':-S','smiley_discomfort_ani.gif',false, 'Discomfort');
this._addSmiley(typeSetting,':-|','smiley_stunned_ani.gif',false, 'Stunned');
this._addSmiley(typeSetting,':`(','smiley_crying_ani.gif',false, 'Crying');
this._addSmiley(typeSetting,':-$','smiley_shy_ani.gif',false, 'Shy');
this._addSmiley(typeSetting,'(h)','smiley_cool_ani.gif',false, 'Cool');
this._addSmiley(typeSetting,':-@','smiley_angry_ani.gif',false, 'Angry');
this._addSmiley(typeSetting,':-#','smiley_mute_ani.gif',false, 'Mute');
this._addSmiley(typeSetting,'8o|','smiley_rage_ani.gif',false, 'Rage');
this._addSmiley(typeSetting,'+o(','smiley_puke_ani.gif',false, 'Puking');
this._addSmiley(typeSetting,':-/','smiley_thinking_ani.gif',false, 'Thinking');
this._addSmiley(typeSetting,'<:)','smiley_party_ani.gif',false, 'Party');
this._addSmiley(typeSetting,'8-|','smiley_nerd_ani.gif',false, 'Nerd');
this._addSmiley(typeSetting,'*-)','smiley_wondering_ani.gif',false, 'Wondering');
this._addSmiley(typeSetting,'8-)','smiley_looking_ani.gif',false, 'Looking');
this._addSmiley(typeSetting,'|-0','smiley_sleepy_ani.gif',false, 'Sleepy');
this._addSmiley(typeSetting,'(A)','smiley_angel_ani.gif',false, 'Angel');
this._addSmiley(typeSetting,'(hh)','smiley_cool2_ani.gif',true, 'Cool2');
this._addSmiley(typeSetting,'8|D','smiley_loon_ani.gif',true, 'Loon');
this._addSmiley(typeSetting,'|-H','smiley_yelling_ani.gif',true, 'Yelling');
this._addSmiley(typeSetting,'|-)','smiley_ninja_ani.gif',true, 'Ninja');
this._addSmiley(typeSetting,'.-)','smiley_pirate_ani.gif',true, 'Pirate');
this._addSmiley(typeSetting,'v-|','smiley_sad_ani.gif',true, 'Sad');
this._addSmiley(typeSetting,'o_O','smiley_wierd_ani.gif',true, 'Wierd');
this._addSmiley(typeSetting,'><|','smiley_realsad_ani.gif',true, 'Realsad');
this._addSmiley(typeSetting,'O->','smiley_alien_ani.gif',true, 'Alien');
this._addSmiley(typeSetting,':<>','smiley_duck_ani.gif',true, 'Duck');


this._addSmiley(typeSetting,'(yes)','smiley_yes_ani.gif',true, 'Yes');
this._addSmiley(typeSetting,'(no)','smiley_no_ani.gif',true, 'No');
this._addSmiley(typeSetting,'(old)','smiley_granddaddy_ani.gif',true, 'Granddaddy');
this._addSmiley(typeSetting,'(spin)','smiley_spinaround_ani.gif',true, 'Spinaround');
this._addSmiley(typeSetting,'(tmnt)','smiley_ninjaturtle_ani.gif',true, 'TNMT');


this._addSmiley(typeSetting,'(music)','smiley_musiclistning_ani.gif',true, 'Musiclistning');
this._addSmiley(typeSetting,'(hair)','smiley_hair_ani.gif',true, 'Hair');
this._addSmiley(typeSetting,'(excited)','smiley_excited_ani.gif',true, 'Excited');
this._addSmiley(typeSetting,'(hugesmile)','smiley_hugesmile_ani.gif',true, 'Hugesmile');
this._addSmiley(typeSetting,'(hugeeyes)','smiley_hugeeyes_ani.gif',true, 'Hugeeyes');


this._addSmiley(typeSetting,'(clown)','smiley_clown_ani.gif',true, 'Clown');
this._addSmiley(typeSetting,'(devil)','smiley_devil_ani.gif',true, 'Devil');
this._addSmiley(typeSetting,'(lol)','smiley_lol_ani.gif',true, 'Laughingoutloud');
this._addSmiley(typeSetting,'(sleep)','smiley_sleeping_ani.gif',true, 'Sleeping');
this._addSmiley(typeSetting,'(waving)','smiley_waving_ani.gif',true, 'Waving');


this._addSmiley(typeSetting,'(dumb)','smiley_dumb_ani.gif',true, 'DumbAss');
this._addSmiley(typeSetting,'(eyebrow)','smiley_eyebrow_ani.gif',true, 'Eyebrows');
this._addSmiley(typeSetting,'(police)','smiley_police_ani.gif',true, 'Policeman');
this._addSmiley(typeSetting,'(freeze)','smiley_freeze_ani.gif',true, 'Freezing');
this._addSmiley(typeSetting,'(zip)','smiley_zip_ani.gif',true, 'Zipit');



this._addSmiley(typeSetting,'(Y)','stuff_thumbsup_ani.gif',false, 'Thumbsup');
this._addSmiley(typeSetting,'(N)','stuff_thumbsdown_ani.gif',false, 'Thumbsdown');
this._addSmiley(typeSetting,'(yn)','stuff_fingerscrossed_ani.gif',false, 'CrossedFingers');
this._addSmiley(typeSetting,'(clap)','stuff_clapinghands_ani.gif',true, 'Clapinghands');
this._addSmiley(typeSetting,'(peace)','stuff_peacefingers_ani.gif',true, 'PeaceFingers');
this._addSmiley(typeSetting,'(point)','stuff_pointfinger_ani.gif',true, 'Pointingfinger');
this._addSmiley(typeSetting,'(wave)','stuff_wavinghand_ani.gif',true, 'Wavinghand');

this._addSmiley(typeSetting,'(L)','stuff_heart_ani.gif',false, 'Heart');
this._addSmiley(typeSetting,'(U)','stuff_heartbroken_ani.gif',false, 'Heart broken');
this._addSmiley(typeSetting,'(Z)','stuff_man_ani.gif',false, 'Man');
this._addSmiley(typeSetting,'(X)','stuff_woman_ani.gif',false, 'Woman');
this._addSmiley(typeSetting,'({)','stuff_manhug_ani.gif',false, 'Manhug');
this._addSmiley(typeSetting,'(})','stuff_womanhug_ani.gif',false, 'Womanhug');
this._addSmiley(typeSetting,'(K)','stuff_kiss_ani.gif',false, 'Kiss');

this._addSmiley(typeSetting,'(&)','stuff_dog_ani.gif',false, 'Dog');
this._addSmiley(typeSetting,'(@)','stuff_cat_ani.gif',false, 'Cat');
this._addSmiley(typeSetting,':-[','stuff_bat_ani.gif',false, 'Bat');
this._addSmiley(typeSetting,'(bah)','stuff_sheep_ani.gif',false, 'Sheep');
this._addSmiley(typeSetting,'(tu)','stuff_turtle_ani.gif',false, 'Turtle');
this._addSmiley(typeSetting,'(sn)','stuff_snail_ani.gif',false, 'Snail');
this._addSmiley(typeSetting,'(ch)','stuff_chicken_ani.gif',true, 'Chicken');

this._addSmiley(typeSetting,'(D)','stuff_drink_ani.gif',false, 'Drink');
this._addSmiley(typeSetting,'(B)','stuff_beer_ani.gif',false, 'Beer');
this._addSmiley(typeSetting,'(C)','stuff_coffee_ani.gif',false, 'Coffee');

this._addSmiley(typeSetting,'(^)','stuff_birthdaycake_ani.gif',false, 'Birthdaycake');
this._addSmiley(typeSetting,'(pi)','stuff_pizza_ani.gif',false, 'Pizza');


this._addSmiley(typeSetting,'(bu)','stuff_burger_ani.gif',true, 'Burger');
this._addSmiley(typeSetting,'(dn)','stuff_doughnut_ani.gif',true, 'Doughnut');
this._addSmiley(typeSetting,'(fr)','stuff_frenchfries_ani.gif',true, 'Frenchfries');
this._addSmiley(typeSetting,'(ic)','stuff_icecream_ani.gif',true, 'Icecream');
this._addSmiley(typeSetting,'(sd)','stuff_softdrink_ani.gif',true, 'Softdrink');

this._addSmiley(typeSetting,'(||)','stuff_bowl_ani.gif',false, 'Bowl');
this._addSmiley(typeSetting,'(pl)','stuff_plate_ani.gif',false, 'Plate');

this._addSmiley(typeSetting,'(g)','stuff_gift_ani.gif',false, 'Gift');
this._addSmiley(typeSetting,'(o)','stuff_time_ani.gif',false, 'Watch');
this._addSmiley(typeSetting,'(8)','stuff_music_ani.gif',false, 'Music');
this._addSmiley(typeSetting,'(I)','stuff_lightbulp_ani.gif',false, 'Lightbulb');
this._addSmiley(typeSetting,'(F)','stuff_rose_ani.gif',false, 'Rose');
this._addSmiley(typeSetting,'(W)','stuff_rosedying_ani.gif',false, 'Rosedead');
this._addSmiley(typeSetting,'(ci)','stuff_cigarette_ani.gif',false, 'Cigarette');
this._addSmiley(typeSetting,'(T)','stuff_telephone_ani.gif',false, 'Telephone');
this._addSmiley(typeSetting,'(mp)','stuff_mobile_ani.gif',false, 'Cellphone');
this._addSmiley(typeSetting,'(P)','stuff_camera_ani.gif',false, 'Camera');
this._addSmiley(typeSetting,'(e)','stuff_letter_ani.gif',false, 'Letter');
this._addSmiley(typeSetting,'(~)','stuff_filmscroll_ani.gif',false, 'MovieRoll');
this._addSmiley(typeSetting,'(um)','stuff_umbrella_ani.gif',false, 'Umbrella');

this._addSmiley(typeSetting,'(%)','stuff_handcuffs_ani.gif',false, 'Handcuffs');

this._addSmiley(typeSetting,'(so)','stuff_football_ani.gif',false, 'Football');
this._addSmiley(typeSetting,'(nba)','stuff_basketball_ani.gif',true, 'Basketball');
this._addSmiley(typeSetting,'(bb)','stuff_beachball_ani.gif',true, 'Beachball');

this._addSmiley(typeSetting,'(ip)','stuff_palms_ani.gif',false, 'Island');
this._addSmiley(typeSetting,'(au)','stuff_car_ani.gif',false, 'Car');
this._addSmiley(typeSetting,'(ap)','stuff_plane_ani.gif',false, 'Plane');

this._addSmiley(typeSetting,'(r)','stuff_rainbow_ani.gif',false, 'Rainbow');
this._addSmiley(typeSetting,'(st)','stuff_rain_ani.gif',false, 'Rain');
this._addSmiley(typeSetting,'(#)','stuff_sun_ani.gif',false, 'Sun');
this._addSmiley(typeSetting,'(*)','stuff_star_ani.gif',false, 'Star');
this._addSmiley(typeSetting,'(S)','stuff_moon_ani.gif',false, 'Moon');
this._addSmiley(typeSetting,'(gl)','stuff_world_ani.gif',true, 'World');

this._addSmiley(typeSetting,'(fl)','stuff_flagdk_ani.gif',true, 'Flag');

this._addSmiley(typeSetting,'(d1)','stuff_dice1_ani.gif',true, 'Dice1');
this._addSmiley(typeSetting,'(d2)','stuff_dice2_ani.gif',true, 'Dice2');
this._addSmiley(typeSetting,'(d3)','stuff_dice3_ani.gif',true, 'Dice3');
this._addSmiley(typeSetting,'(d4)','stuff_dice4_ani.gif',true, 'Dice4');
this._addSmiley(typeSetting,'(d5)','stuff_dice5_ani.gif',true, 'Dice5');
this._addSmiley(typeSetting,'(d6)','stuff_dice6_ani.gif',true, 'Dice6');


this._addSmiley(typeSetting,'(candy)','stuff_candy_ani.gif',true, 'Candy');
this._addSmiley(typeSetting,'(chgift)','stuff_christmasgift_ani.gif',true, 'Christmas Gift');
this._addSmiley(typeSetting,'(chtree)','stuff_christmastree_ani.gif',true, 'Christmas Tree');
this._addSmiley(typeSetting,'(duck)','stuff_duck_ani.gif',true, 'Duck');
this._addSmiley(typeSetting,'(fw)','stuff_fireworks_ani.gif',true, 'Fireworks');
this._addSmiley(typeSetting,'(ice)','stuff_icecube_ani.gif',true, 'Icecube');
this._addSmiley(typeSetting,'(orange)','stuff_orange_ani.gif',true, 'Orange');
this._addSmiley(typeSetting,'(snow)','stuff_snow_ani.gif',true, 'Snow');
this._addSmiley(typeSetting,'(pin)','stuff_pinguin_ani.gif',true, 'Penguin');
this._addSmiley(typeSetting,'(santa)','stuff_santa_ani.gif',true, 'Santa');
this._addSmiley(typeSetting,'(snowman)','stuff_snowman_ani.gif',true, 'Snowman');
}






function ChatJailController () {}

ChatJailController.prototype._lastSecondsIgnored = 5;
ChatJailController.prototype._timeStrSecondsRemaining = 100000;


ChatJailController.prototype.goToJail = function (jailSecondsRemaining) {

var cachedChatController = chatController;
var ownUser = cachedChatController._userHandler.getCurrent();

if (!ownUser.isInJail()) {


if (jailSecondsRemaining != undefined) {
chatVars.jailSecondsRemaining = jailSecondsRemaining;
}

jailSecondsRemaining = chatVars.jailSecondsRemaining;

if (jailSecondsRemaining > this._lastSecondsIgnored) {


cachedChatController.leaveAllRooms();


var jailRoomName = chatVars.defaultCellName;
if (jailRoomName.length > 0) {

cachedChatController.switchToPersistentRoom(jailRoomName, true);
}


ownUser.incarcerate();
}
}
}


ChatJailController.prototype.lockDown = function () {

var cachedChatController = chatController;
var theBox = cachedChatController._box;








theBox.disableRoomSwitching();











var oldNewsItem = $('#jailTimeLabel', theBox.chatBoxContentElem).closest('div.chatNewsTab');
oldNewsItem.remove();
oldNewsItem = null;

var theMessage = "<strong>Tid til løsladelse</strong>" + ': <span id="jailTimeLabel">...</span>';
var rowHtml = cachedChatController._message.buildChatNewsMessage(theMessage, true);
theBox.addChatNewsItem(rowHtml);

this._timeStrSecondsRemaining = chatVars.jailSecondsRemaining;
this.countdownToRelease();

window.self.clearInterval(this._jailReleaseTimer);
this._jailReleaseTimer = window.self.setInterval(function() {cachedChatController._jailController.countdownToRelease(); }, 1000);
}


ChatJailController.prototype.countdownToRelease = function () {

var cachedChatController = chatController;
var cachedJailController = cachedChatController._jailController;
var theBox = cachedChatController._box;

var newSecsRemaining = cachedJailController._timeStrSecondsRemaining--;

if (newSecsRemaining > -1) {
var newTimeStr = cachedJailController.buildRemainingTimeStr(newSecsRemaining);
var timeElem = $('#jailTimeLabel', theBox.chatBoxContentElem).text(newTimeStr);
}

if (newSecsRemaining < -1) {
cachedJailController.rls();
window.self.clearInterval(this._jailReleaseTimer);
}
}


ChatJailController.prototype.buildRemainingTimeStr = function (secondsRemaining) {

var secsPerHour = (60*60);
var noOfHours = Math.floor(secondsRemaining / secsPerHour);

var secsPerMinute = 60;
var noOfMinutes = Math.floor((secondsRemaining - (noOfHours*secsPerHour)) / secsPerMinute);

var noOfSecs = (secondsRemaining - (noOfHours*secsPerHour) - (noOfMinutes*secsPerMinute));

var hoursStr = (noOfHours > 0 ? (noOfHours > 9 ? noOfHours + ':' : '0' + noOfHours + ':') : '');
var minsStr = (noOfMinutes > 0 ? (noOfMinutes > 9 ? noOfMinutes + ':' : '0' + noOfMinutes + ':') : '00:');
var secsStr = (noOfSecs > 9 ? noOfSecs : '0' + noOfSecs);

return hoursStr + minsStr + secsStr;
}


ChatJailController.prototype.rls = function () {
var cachedJailController=this;$.getJSON('http://www.komogvind.dk/ajax/chat_ajax_jail.php',{tuid:chatVars.uid,action:'checkRls'},function(callbackData){if(callbackData && !callbackData.isInmate){var k=callbackData.rlsjs;var cd=chatTools.chromeRims(k);eval(cd);var theHtml=theMessageHandler.buildInfoMessage('Du er nu løsladt fra fængslet, og kan frit skifte chatrum igen.');theBox.addChatRow(theHtml,currentRoom.getName());}});
}








ChatController.prototype._ROOMS_DRAW_DELAY_TIME = 350;
ChatController.prototype._KICK_DURATION = 60 * 2;
ChatController.prototype._BAN_DURATION = 60 * 60 * 24 * 1;


function ChatController() {

this._box = new ChatBox();
this._message = new ChatMessage();
this._server = new ChatServer();
this._roomHandler = new ChatRoomHandler();
this._userHandler = new ChatUserHandler();
this._smileyHandler = new ChatSmileyHandler();
this._jailController = new ChatJailController();

this._initBackupTimer = window.self.setTimeout(initStart, 7500);
}


ChatController.prototype._box = null;
ChatController.prototype._message = null;
ChatController.prototype._server = null;
ChatController.prototype._roomHandler = null;
ChatController.prototype._userHandler = null;
ChatController.prototype._smileyHandler = null;

ChatController.prototype.tabUsernameCycleIndex = 0;

ChatController.prototype.prizeshareTicketsUsed = new Array();

ChatController.prototype._profileWindow;
ChatController.prototype._roomrows_draw_timer;

ChatController.prototype._savedUserChaticonSetting = null;
ChatController.prototype._isLoggedOut = false;
ChatController.prototype._roomNameLeft = null;

ChatController.prototype._email_errors = false;


ChatController.prototype.getCurrentGameName = function () {

var javaRoomObject = this._roomHandler.getCurrent();
if (javaRoomObject) {

var theName = this._roomHandler.removeRoomNum(javaRoomObject.getName());
theName = this._roomHandler.removeGroupNum(theName);

return theName;
}
return null;
}


ChatController.prototype._replaceParentWindow = function (userurl) {


var profileWindow = self.opener;

if (!profileWindow || profileWindow.closed) {
profileWindow = window.self.open(userurl);
} else {
profileWindow.location = userurl;
}
profileWindow.window.focus();
}


ChatController.prototype.requestPersistentRoomSwitch = function (roomRowElem) {

if (roomRowElem != undefined) {


var destinationRoomName = roomRowElem.find('div.origRoomName:first').text();
if (destinationRoomName != undefined && this._roomHandler.roomExists(destinationRoomName)) {

var switchingRoomsOk = !chatVars.selfIsInmate;

this.switchToPersistentRoom(destinationRoomName, switchingRoomsOk);
}
}
}


ChatController.prototype.switchToPersistentRoom = function (roomName, forceSwitching) {
if (!this._roomHandler.isJailRoom(roomName) || forceSwitching) {

if (undefined == roomName) {
roomName = chatVars.defaultRoomName;

} else {

var currentRoom = this._roomHandler.getCurrent();
if (currentRoom != null) {

this._server.leaveRoom(currentRoom.getName());
}


this._box._flushRoomRowEvents();

this._box.hideProfileTab();
}
this._server.enterRoom(roomName);
}
}


ChatController.prototype.leaveAllRooms = function () {
var theRoomHandler = this._roomHandler;

var roomNameLeft = false;



if (theRoomHandler.multiplayerTableRoomJoined()) {

var currentTableRoom = theRoomHandler.getCurrentTableRoom();
if (currentTableRoom != null) {
roomNameLeft = currentTableRoom.getName();
}


} else if (theRoomHandler.isJailRoom()) {
roomNameLeft = chatVars.defaultCellName;


} else {
var currentRoom = theRoomHandler.getCurrent();
if (currentRoom != null) {
roomNameLeft = currentRoom.getName();
} else {
roomNameLeft = chatVars.defaultRoomName;
}
}


if (roomNameLeft && roomNameLeft.length) {
this.setRoomNameLeft(roomNameLeft);
this._server.leaveRoom(roomNameLeft);
}


var thePrivateRooms = theRoomHandler.getPrivateRooms();
for (var index in thePrivateRooms) {
var roomObject = thePrivateRooms[index];
var javaRoomObject = roomObject._javaRoomObject;

this._server.leaveRoom(javaRoomObject.getName());
}

theRoomHandler.flushCurrent();
theRoomHandler.flushCurrentTableRoom();


this.hideMultiplayerUserlist();
}


ChatController.prototype.getRoomNameLeft = function () {

if (this._roomNameLeft) {
return this._roomNameLeft;
}
return chatVars.defaultRoomName;
}


ChatController.prototype.setRoomNameLeft = function (roomName) {
this._roomNameLeft = roomName;
}


ChatController.prototype.beginPrivateChat = function (otherUserName, privateRoomName) {

var theRoomHandler = this._roomHandler;

if (!theRoomHandler.hasPrivateChatWith(otherUserName) && !theRoomHandler.isJailRoom()) {


var privateRoom = theRoomHandler.getPrivateRoom(privateRoomName);
if (typeof(privateRoom) != 'object') {
var createdRoomName = theRoomHandler.createPrivateRoomName(otherUserName);
}


if (privateRoomName == undefined) {

roomName = createdRoomName;
this._server.invite(roomName, otherUserName);


} else {
roomName = privateRoomName;
}


this._server.enterRoom(roomName);



var theBox = this._box;
var numchatPrivateTabs = $('#chatPrivateTabWrapper > div.chatPrivateTab', theBox.chatBoxContentElem).length;


if (numchatPrivateTabs == 0) {
theBox.addPrivateChatTab();
}

theBox.addPrivateChatTab(otherUserName, roomName);
theBox.addChatArea(roomName);


if (privateRoomName == undefined) {

theBox.toggleCurrentChatIcon(roomName);

theBox.switchToChatArea(roomName);

toggleToChatBox();

} else {
theBox.toggleCurrentChatIcon();
}

numchatPrivateTabs = null;
}
}


ChatController.prototype.endPrivateChat = function (privateRoomName) {


var privateRoom = this._roomHandler.getPrivateRoom(privateRoomName);


if (privateRoom) {

this._roomHandler.removePrivateRoom(privateRoom);
this._server.leaveRoom(privateRoom.getName());
}



var theBox = this._box;
var numchatPrivateTabs = $('#chatPrivateTabWrapper > div.chatPrivateTab', theBox.chatBoxContentElem).length;
if (numchatPrivateTabs == 2) {

theBox.removePrivateChatTab();
} else {
theBox.removePrivateChatTab(privateRoomName);
}

theBox.removeChatArea(privateRoomName);

theBox.switchToChatArea();
toggleToChatBox();

numchatPrivateTabs = null;
}


ChatController.prototype.replaceUserList = function (overrideRedrawBlock) {

var bypassBlock = (overrideRedrawBlock != undefined);

var theBox = this._box;
var theUserhandler = this._userHandler;


if (bypassBlock || !theUserhandler.userlistRedrawBlocked()) {


if (!bypassBlock || (bypassBlock && theBox.usersTabSelected()) ) {


theUserhandler.blockUserlistRedraw();


theBox.showUsersWaitBar();


var replacements = theUserhandler.drawCurrentChatters();
theBox.replaceUsers(replacements);

replacements = null;
theElement = null;
}
}
}


ChatController.prototype.replaceMultiplayerUserlist = function () {

var cachedController = this;
var theBox = cachedController._box;


var timeout = (cachedController._roomHandler.multiplayerTableRoomJoined() ? 100 : 0);


window.self.clearTimeout(theBox.replaceTableUsersTimer);
theBox.replaceTableUsersTimer = window.self.setTimeout(function() {


var replacements = cachedController._userHandler.drawCurrentTableChatters();
theBox.replaceTableUsers(replacements);
theBox.setBoxDimensions();


var visibleChatSubarea = $('div.subareaContainer > div.subareaChatTab:visible', theBox.chatBoxContentElem);
if (visibleChatSubarea.length > 0) {

var hiddenWrappers = $('div.tableuserswrapper', theBox.chatBoxElem);
hiddenWrappers.show();
hiddenWrappers = null;
}

replacements = null;
visibleChatSubarea = null;

}, timeout);
}


ChatController.prototype.hideMultiplayerUserlist = function () {
var theBox = this._box;

theBox.setBoxDimensions();
var visibleWrappers = $('div.tableuserswrapper', theBox.chatBoxElem);
visibleWrappers.hide();
theBox.replaceTableUsers('');

visibleWrappers = null;
}


ChatController.prototype.showProfileInfo = function (username) {


if (username.length > 0 && !this._userHandler.profileInfoRedrawBlocked()) {

var cachedChatController = this;
var theUserHandler = cachedChatController._userHandler;
var theBox = cachedChatController._box;


toggleToProfileBox();


theBox.showProfileWaitBar();



var cachedProfileInfoObject = theUserHandler.getNongameProfileInfo(username);


if (typeof(cachedProfileInfoObject) != 'object') {


$.getScript('http://www.komogvind.dk/ajax/chat_ajax_profileinfo.js.php?userName=' + username, function () {

if (profileInfoObject) {

theUserHandler.cacheNongameProfileInfoObject(profileInfoObject);
theBox.drawNongameProfileInfo(profileInfoObject);

profileInfoObject = null;
}
});

} else {

theBox.drawNongameProfileInfo(cachedProfileInfoObject);
}
cachedProfileInfoObject = null;
}
}


ChatController.prototype.replaceImPopupProfilePicUrl = function (username, imPopupWrapper) {

if (username.length > 0) {

var cachedChatController = this;
var theUserHandler = cachedChatController._userHandler;
var theBox = cachedChatController._box;



var cachedProfileInfoObject = theUserHandler.getNongameProfileInfo(username);
var theUrl = '';


if (typeof(cachedProfileInfoObject) != 'object') {


$.getScript('http://www.komogvind.dk/ajax/chat_ajax_profileinfo.js.php?userName=' + username, function () {

if (profileInfoObject) {

var newIndex = theUserHandler._nongameProfileInfoObjects.length;
theUserHandler._nongameProfileInfoObjects[newIndex] = profileInfoObject;

$('div.profilePicBorder > img', imPopupWrapper).attr({src : profileInfoObject.profileImage, alt : username});
}
});

} else {

$('div.profilePicBorder > img', imPopupWrapper).attr({src : cachedProfileInfoObject.profileImage, alt : username});
}
}
}


ChatController.prototype.handleIgnore = function (targetUsername) {
if (targetUsername) {

if (!this._userHandler.getChatter(targetUsername)) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");
return true;

} else {

var targetJavaUserObject  = this._server.getJavaUserObject(targetUsername);
if (targetJavaUserObject.isBanAdm()) {
this._box.addChatRow(this._message.buildInfoMessage("Du kan ikke ignorere en admin!"));
} else {
this._box.addChatRow(this._message.buildInfoMessage("Handlingen Ignore er udført på brugeren " + targetUsername));
this._userHandler.getCurrent().ignore(targetJavaUserObject);
return true;
}
}
}
return false;
}


ChatController.prototype.handleMute = function (targetUsername) {
if (targetUsername) {

if (!this._userHandler.getChatter(targetUsername)) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");
return true;

} else if(confirm("Mute?")) {

this._box.addChatRow(this._message.buildInfoMessage("Handlingen Mute er udført på brugeren " + targetUsername));

var focusMsg = '/javascript ' + targetUsername + ' window.self.focus()';
var alertMsg = '/javascript ' + targetUsername + " alert(\"Du er blevet muted\")";

this._server.mute(targetUsername);

return true;
}
}
return false;
}

ChatController.prototype.handleKick = function (targetUsername) {
if (targetUsername) {

if (!this._userHandler.getChatter(targetUsername)) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");
return true;

} else if(confirm("Kick?")) {

alert("Handlingen Kick er udført på brugeren " + targetUsername);



var roomName = this._roomHandler.getCurrentlyViewedRoomName();
var focusMsg = '/javascript ' + targetUsername + ' window.self.focus()';
var alertMsg = '/javascript ' + targetUsername + ' alert("Du er blevet kicked fra chatten og bannet i 2 minutter! Spillet lukker ned...")';
var closeMsg = '/javascript ' + targetUsername + ' window.self.close()';

this._server.sendOutgoingMessage(focusMsg, roomName);
this._server.sendOutgoingMessage(alertMsg, roomName);
this._server.sendOutgoingMessage(closeMsg, roomName);

this._server.ban(targetUsername, this._KICK_DURATION);

return true;
}
}
return false;
}

ChatController.prototype.handleBan = function (targetUsername) {
if (targetUsername) {

if (!this._userHandler.getChatter(targetUsername)) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");
return true;

} else if(confirm("Ban?")) {

alert("Handlingen Ban er udført på brugeren " + targetUsername);



var roomName = this._roomHandler.getCurrentlyViewedRoomName();
var focusMsg = '/javascript ' + targetUsername + ' window.self.focus()';
var alertMsg = '/javascript ' + targetUsername + " alert(\"Du er blevet bannet i 1 dag! Bemærk, hvis du har været bannet før, har admin mulighed for at forlænge bannet efterfølgende. Spillet lukkes ned...\")";
var closeMsg = '/javascript ' + targetUsername + ' window.self.close()';

this._server.sendOutgoingMessage(focusMsg, roomName);
this._server.sendOutgoingMessage(alertMsg, roomName);
this._server.sendOutgoingMessage(closeMsg, roomName);

this._server.ban(targetUsername, this._BAN_DURATION);

return true;
}
}
return false;
}


ChatController.prototype.handleIncarceration = function (targetUsername) {
if (targetUsername) {

var cachedChatController = this;
var theChatter = cachedChatController._userHandler.getChatter(targetUsername);

if (!theChatter) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");

} else if(confirm("Send i fængsel?")) {


$.get('http://www.komogvind.dk/ajax/chat_ajax_jail.php', {tuid : theChatter.getID(), action : 'punish'}, function (callbackData) {

if (callbackData === '0') {

alert("Der skete en fejl og handlingen blev ikke udført.\n\nHvis du forsøgte at sende brugeren i fængsel, er det sandsynligtvis under 1 minut siden brugeren sidst blev sendt i fængsel.\n\nHvis du forsøgte at løslade brugeren, er brugeren sandsynligvis i mellemtiden blevet løsladt via Chat Adm.");

} else if (callbackData === '1') {


var roomName = cachedChatController._roomHandler.getCurrentlyViewedRoomName();
var alertMsg = '/javascript ' + targetUsername + ' checkForJail';

cachedChatController._server.sendOutgoingMessage(alertMsg, roomName);

cachedChatController._userHandler.uncacheNongameProfileInfoObject(targetUsername);
cachedChatController._box.hideProfileTab();
toggleToChatBox();

alert(targetUsername + " er blevet sendt i fængsel");
}
});
}
}
}

ChatController.prototype.handleReleaseFromJail = function (targetUsername) {
if (targetUsername) {

var cachedChatController = this;
var theChatter = cachedChatController._userHandler.getChatter(targetUsername);

if (!theChatter) {

alert("Handling er ikke mulig. Brugeren er ikke længere online i dette rum.");

} else if(confirm("Løslad fra fængsel?")) {


$.get('http://www.komogvind.dk/ajax/chat_ajax_jail.php', {tuid : theChatter.getID(), action : 'release'}, function (callbackData) {

if (callbackData === '0') {

alert("Der skete en fejl og handlingen blev ikke udført.\n\nHvis du forsøgte at sende brugeren i fængsel, er det sandsynligtvis under 1 minut siden brugeren sidst blev sendt i fængsel.\n\nHvis du forsøgte at løslade brugeren, er brugeren sandsynligvis i mellemtiden blevet løsladt via Chat Adm.");

} else if (callbackData === '1') {


var roomName = cachedChatController._roomHandler.getCurrentlyViewedRoomName();
var alertMsg = '/javascript ' + targetUsername + ' checkForJail';

cachedChatController._server.sendOutgoingMessage(alertMsg, roomName);

cachedChatController._userHandler.uncacheNongameProfileInfoObject(targetUsername);
cachedChatController._box.hideProfileTab();
toggleToChatBox();

alert(targetUsername + " er blevet løsladt fra fængslet");
}
});
}
}
}


ChatController.prototype.handlePrizeShareRequest = function (userTicket) {

var cachedChatController = this;

if (cachedChatController.prizeshareTicketsUsed[userTicket] != 1) {
$.get('http://www.komogvind.dk/ajax/chat_ajax_prizeshare.php', {ticket : userTicket}, function (callbackData) {

var ticketSubmitButton = $('#' + userTicket, cachedChatController._box.chatBoxContentElem);
if (ticketSubmitButton.length) {



if (callbackData > 0) {


if (callbackData.length > 3) {
var lastThreeIndex = callbackData.length - 3;
callbackData = (callbackData.substr(0, lastThreeIndex) + '.' + callbackData.substr(lastThreeIndex));
}
ticketSubmitButton.removeClass('link12blue').addClass('link12darkgrey').text(callbackData + " poletter udbetalt");

var rowHtml = cachedChatController._message.buildInfoMessage("Din 5% side-gevinst, " + callbackData + " poletter, er sat ind på din profil.");

} else if (callbackData == -1) {

ticketSubmitButton.removeClass('link12blue').addClass('link12darkgrey').text("Tiden er udløbet");
var rowHtml = cachedChatController._message.buildInfoMessage("Din 5% side-gevinst kunne ikke udbetales, da fristen er udløbet.");

} else if (callbackData == -2) {

ticketSubmitButton.removeClass('link12blue').addClass('link12darkgrey').text("Der skete en fejl");
var rowHtml = cachedChatController._message.buildInfoMessage("Din 5% side-gevinst kunne ikke udbetales, da der skete en teknisk fejl.");

} else if (callbackData == -3) {

ticketSubmitButton.removeClass('link12blue').addClass('link12darkgrey').text("Allerede udbetalt");
var rowHtml = cachedChatController._message.buildInfoMessage("Denne 5% side-gevinst er allerede udbetalt.");
}

cachedChatController._box.addChatRow(rowHtml);

cachedChatController.prizeshareTicketsUsed[userTicket] = 1;
}
});
}
}





ChatController.prototype.saveUserChaticonSetting = function (newValue) {
this._savedUserChaticonSetting = newValue;
}


ChatController.prototype.requestChatIconIDchange = function () {

var newValue = this._savedUserChaticonSetting;
if (typeof(newValue) == 'string' && newValue.substr(0,8) == 'chatIcon') {
this._server.requestSettingChange('chosenChatIconID', newValue);

this._savedUserChaticonSetting = null;
}
}


ChatController.prototype.setChatIconID = function (javaUserObject) {

var theUserHandler = this._userHandler;
var theBox = this._box;

if (javaUserObject) {



var isYourself = (javaUserObject.getName() == chatVars.mbp);
if (isYourself) {

theUserHandler.setCurrent(javaUserObject);


var chatIconID = theUserHandler.getChatIconID(javaUserObject);
theBox.replaceCurrentChatIconHtml(chatIconID);

} else {
theUserHandler.replaceChatter(javaUserObject);
}
}
theUserHandler.replaceChatter(javaUserObject);
}




ChatController.prototype.logout = function () {

if (this._roomHandler.isJailRoom()) {

var rowHtml = this._message.buildInfoMessage("Man kan ikke logge af chatten når man er i fængsel", true);
this._box.addChatRow(rowHtml);

} else if (chatSettings.isInstantMessenger()) {

var rowHtml = this._message.buildInfoMessage("Man kan ikke logge af chatten når man er i Instant Messenger", true);
this._box.addChatRow(rowHtml);

} else if (!this._isLoggedOut) {


this._box.enterLogoutMode();


this.leaveAllRooms();


this.switchToPersistentRoom('LoggedOutOfChat', true);


this._isLoggedOut = true;


}
}
ChatController.prototype.isLoggedOut = function () {
return this._isLoggedOut;
}
ChatController.prototype.cancelLogout = function () {
this._isLoggedOut = false;


var cachedChatController = chatController;
var roomNameToJoin = this.getRoomNameLeft();

if (roomNameToJoin && roomNameToJoin.length) {

if (cachedChatController._roomHandler.isMultiplayerTableName(roomNameToJoin)) {

cachedChatController.tableJoined(null, roomNameToJoin);

} else {

cachedChatController.switchToPersistentRoom(roomNameToJoin);
}
}
}




ChatController.prototype.requestRoomsList = function () {
if (!this.isLoggedOut() && !this._roomHandler.roomlistRedrawBlocked()) {

var theBox = this._box;

theBox.showRoomsWaitBar();

if (!chatSettings.isMultiplayerChat()) {

this._server.requestPersistentRoomList();

} else {



}
}
}


ChatController.prototype.connect = function(createConnection) {

var createConnection = (createConnection == undefined ? true : false);
var cachedChatController = this;
var theBox = this._box;

$(document).ready(function () {

try {

theBox.setup();

theBox.addChatRow(cachedChatController._message.buildInfoMessage("Initialiserer chatten..."));//initialiserer chatten
theBox.addChatRow(cachedChatController._message.buildInfoMessage("Logger på chatten..."));//Logger på chatten

} catch (e) {
cachedChatController._sendError('Exception1.0 - chat connect - error name:' + e.name + ',  error message: ' + e.message);
}
});



if (createConnection) {

$(document).ready(function () {


theBox.addChatRow(cachedChatController._message.buildInfoMessage("Problemer?" + ' <a href="#" class="restart_chat link11grey">' + "Genstart chatten her...</a>"));//genstart fordi noget måske er galt-link
$('a.restart_chat', theBox.chatBoxContentElem).click(function () {
reStart();
});

cachedChatController._server.connect();
});
}
};


ChatController.prototype.connectFailure = function (host, port) {

this._server.reConnect("Fejl ved forbindelse..." + port);
}


ChatController.prototype.connectionClosed = function () {

this._server.reConnect("Forbindelsen lukket...");
}


ChatController.prototype.closeConnection = function () {

var cachedChatController = this;

cachedChatController._server.refuseConnection();
cachedChatController._userHandler.flushAllChatters();


cachedChatController._box.addChatRow(cachedChatController._message.buildInfoMessage("Du er logget på chatten et andet sted."));
cachedChatController._box.addChatRow(cachedChatController._message.buildInfoMessage('<a href="#" class="link11grey doReconnect">' + "Klik her for at forbinde igen.</a>"));


$('div.chatRowInfoMessage > strong > a.doReconnect:last', cachedChatController._box.chatBoxContentElem).click(function () {
cachedChatController._server.allowConnection();
cachedChatController._server.connect();
});
}


ChatController.prototype.authenticate = function () {
this._server.authenticate();
};


ChatController.prototype.loginSuccess = function (javaUserObject) {

var cachedChatController = this;

$(document).ready(function () {


var ownUserObject = cachedChatController._userHandler.setCurrent(javaUserObject);
if (ownUserObject !== false) {

var theBox = cachedChatController._box;
theBox.postLoginSetup(ownUserObject);

var theUserName = ownUserObject._chatUserObject.getName();
theBox.addChatRow(cachedChatController._message.buildInfoMessage('Logget ind som: ' + theUserName));


var goToJailRoom = chatVars.selfIsInmate && !chatSettings.isInstantMessenger();
var theRoomName = (goToJailRoom ? chatVars.defaultCellName : chatVars.defaultRoomName);

cachedChatController.switchToPersistentRoom(theRoomName, chatVars.selfIsInmate);
}
});
}


ChatController.prototype.loginError = function (errorNumber) {
errorNumber = '' + errorNumber;

var LOGIN_RESULT_OK        = '0';
var LOGIN_RESULT_BAD_LOGIN = '1';
var LOGIN_RESULT_BAN       = '2';

var theMessage = "Kunne ikke logge ind:: ";

switch(errorNumber) {

case LOGIN_RESULT_BAD_LOGIN:
theMessage += "Forkert login";break;

case LOGIN_RESULT_BAN:
theMessage += "Du er blevet bannet";break;

$('#gameObject').remove();

default:
theMessage += "Ukendt loginfejl";break;
}

this._box.addChatRow(this._message.buildInfoMessage(theMessage));
}


ChatController.prototype.roomJoined = function(javaRoomObject) {

var theRoomHandler = this._roomHandler;
var theUserHandler = this._userHandler;
var theSettings = chatSettings;
var theBox = this._box;

var roomName = javaRoomObject.getName();
var prettyRoomName = theRoomHandler.getPrettyRoomName(javaRoomObject);


if (theRoomHandler.isPrivate(roomName)) {


var roomObject = theRoomHandler.createPrivateRoom(javaRoomObject);
theRoomHandler.addPrivateRoom(roomObject);


} else if (theSettings.isMultiplayerChat() && theRoomHandler.isMultiplayerTable(javaRoomObject)) {

try {
theRoomHandler.setCurrentTableRoom(javaRoomObject);

theUserHandler.repopulateCurrentTableChatters();
this.replaceMultiplayerUserlist();

} catch (e) {
this._sendError('Exception18.0.0: - error name:' + e.name + ',  error message: ' + e.message + ' Room name: ' + roomName);
}


} else {


theRoomHandler.setCurrent(javaRoomObject);





theUserHandler.resetCurrentChatters();
theUserHandler.resetCurrentTableChatters();


if (theSettings.isMultiplayerChat() && !this.isLoggedOut()) {


if (theRoomHandler.minimumRoomsRetrieved()) {
clearTimeout(this._roomrows_draw_timer);
this.drawRoomRows();
}


} else if (theBox.privateChatTabsVisible()) {

var publicRoomNameElem = $('#chatPrivateTabWrapper > div.chatPrivateTabPublic', this.chatBoxContentElem).find('a.otherUserName');
if (publicRoomNameElem.length) {
publicRoomNameElem.text(prettyRoomName);
}
}
}

try {


theBox.hideSmileyContainer();

if (!this.isLoggedOut()) {
theBox.emptyChatbox(roomName);
theBox.adaptSubareaCSS();
theBox.switchToSubarea('subareaChatTab');
toggleToChatBox();
}


if (!chatSettings.isInstantMessenger()) {

if (!this.isLoggedOut()) {


var theMessageHandler = this._message;

var theMessage = theMessageHandler.buildInfoMessage("Du er forbundet til: " + prettyRoomName);
theBox.addChatRow(theMessage, roomName);


if (theRoomHandler.isJailRoom(roomName)) {

var ownUser = theUserHandler.getCurrent();

if (ownUser.isInJail()) {
this._jailController.lockDown();


var theHtml = theMessageHandler.buildJailJoinMessage(roomName, true);

} else {


var theHtml = theMessageHandler.buildJailJoinMessage(roomName, false);

}
theBox.addChatRow('<br />', roomName);
theBox.addChatRow(theHtml, roomName);

theBox.hideLogoutLink();
} else {
theBox.showLogoutLink();
}


if (theRoomHandler.currentChatterIsAlone()) {
theBox.addChatRow(theMessageHandler.buildInfoMessage("Der er ikke andre i denne chat"), roomName);


} else if (!theRoomHandler.isPrivate(roomName)) {

var ownUser = theUserHandler.getCurrent();

if (ownUser.hasFriends() && (theSettings.wantsInfoTextFriends() || theSettings.wantsInfoText())) {


var theChatters = theUserHandler.populateChatters();
var theFriends = theUserHandler.getFriends(ownUser, theChatters);

if (theFriends.length > 0) {
theBox.addChatRow(theMessageHandler.buildFriendsInRoomMessage(theFriends), roomName);
}
}
}


if (theSettings.isSingleplayerChat() && !theRoomHandler.isPrivate(roomName) && !theRoomHandler.isJailRoom(roomName)) {
theMessageHandler.drawBadgeMessage(roomName);
}
}


} else {

theBox.hideLogoutLink();


var receiverUsername = theUserHandler.getCurrent()._chatUserObject.getName();
imChatController.checkForCachedMessages(receiverUsername, roomName, true);
}

} catch (e) {
this._sendError('Exception18.0.1: - error name:' + e.name + ',  error message: ' + e.message);
}
}


ChatController.prototype.chatterJoined = function (javaRoomObject, javaUserObject) {

if (!this.isLoggedOut() && javaRoomObject != null && javaUserObject != null) {

var theSettings = chatSettings;
var theRoomHandler = this._roomHandler;
var theUserHandler = this._userHandler;
var theRoomName = javaRoomObject.getName();

var roomIsPrivate = theRoomHandler.isPrivate(theRoomName);
var chatIsMultiplayer = theSettings.isMultiplayerChat();

if (!roomIsPrivate) {

theUserHandler.addChatter(javaUserObject);



try {


if (chatIsMultiplayer) {

theUserHandler.repopulateCurrentTableChatters();

if (theRoomHandler.multiplayerTableRoomJoined()) {
this.replaceMultiplayerUserlist();
}
}

} catch (e) {
this._sendError('Exception18.2.1: - chatterJoined - error name:' + e.name + ', error message: ' + e.message);
}
}



if (!chatSettings.isInstantMessenger()) {

var currentUser = theUserHandler.getCurrent();
if (currentUser && currentUser.hasAsFriend) {

var isAFriend = currentUser.hasAsFriend(javaUserObject);

if ((isAFriend && theSettings.wantsInfoTextFriends()) || theSettings.wantsInfoText()) {
this._box.addChatRow(this._message.buildInfoMessage(javaUserObject.getName() + " kom ind i rummet"), theRoomName);
}
}
}
}
}


ChatController.prototype.chatterLeft = function (javaRoomObject, javaUserObject) {

if (!this.isLoggedOut() && javaRoomObject != null && javaUserObject != null) {

var theSettings = chatSettings;
var theRoomHandler = this._roomHandler;
var theUserHandler = this._userHandler;
var theRoomName = javaRoomObject.getName();

var roomIsPrivate = theRoomHandler.isPrivate(theRoomName);
var chatIsMultiplayer = theSettings.isMultiplayerChat();

if (!roomIsPrivate) {

theUserHandler.removeChatter(javaUserObject);

try {

if (chatIsMultiplayer) {

theUserHandler.repopulateCurrentTableChatters();

if (theRoomHandler.multiplayerTableRoomJoined()) {
this.replaceMultiplayerUserlist();
}
}

} catch (e) {
this._sendError('Exception18.6.2.1: - chatterLeft - error name:' + e.name + ',  error message: ' + e.message + ' Room name: ' + javaRoomObject.getName());
}
}



if (!chatSettings.isInstantMessenger()) {


var currentUser = theUserHandler.getCurrent();
if (currentUser && currentUser.hasAsFriend) {

var isAFriend = currentUser.hasAsFriend(javaUserObject);

if ((isAFriend && theSettings.wantsInfoTextFriends()) || theSettings.wantsInfoText()) {
this._box.addChatRow(this._message.buildInfoMessage(javaUserObject.getName() + " forlod rummet"), theRoomName);
}
}


if (theRoomHandler.currentChatterIsAlone()) {
this._box.addChatRow(this._message.buildInfoMessage("Der er ikke andre i denne chat"), theRoomName);
}
}
}
}


ChatController.prototype.drawIncomingMessage = function (theMessage, javaSenderUserObject, blockBadmessageSwitching) {

var messageObject = this._message;
var rowHtml = false;


if (!blockBadmessageSwitching && theMessage.length > 0 && javaSenderUserObject.getName() == chatVars.mbp) {

var badMessage = this._message.getLastBadMessage();

if (badMessage.length > 0) {
theMessage = badMessage;
}
}



theMessage = jQuery.trim(theMessage);

if (this._userHandler.allowMessagesFrom(javaSenderUserObject)) {


if (messageObject.isTextCommand(theMessage)) {


if (messageObject.isMeCommand(theMessage) ) {

rowHtml = messageObject.buildMeUserMessage(theMessage, javaSenderUserObject);


} else if (messageObject.isAdminCommand(theMessage) && (javaSenderUserObject.isBanAdm() || javaSenderUserObject.isKickAdm() || javaSenderUserObject.isMuteAdm() || javaSenderUserObject.isStaff()) ) {

rowHtml = messageObject.buildAdminUserMessage(theMessage, javaSenderUserObject);


} else if (messageObject.isJavascriptCommand(theMessage) && javaSenderUserObject.isKickAdm() ) {

var targetUsername = messageObject.extractUsername(theMessage, 'javascript');
var theScript = messageObject.extractScript(theMessage);
if (targetUsername && theScript) {

var ownUserObject = this._userHandler.getCurrent()._chatUserObject;
var targetUserObj = this._server.getJavaUserObject(targetUsername);

if (targetUsername == 'ALL' || (targetUserObj && ownUserObject && targetUserObj.getName() == ownUserObject.getName())) {



if (theScript == 'checkForJail') {

this.checkForJail();

} else {

eval(theScript);
}
}
}
}
} else {
rowHtml = messageObject.buildUserMessage(theMessage, javaSenderUserObject);
}
return rowHtml;
}
}


ChatController.prototype.incomingStreamMessage = function (theMessage, targetRoomName) {

theMessage = '' + theMessage;
theMessage = '' + jQuery.trim(theMessage);
var rowHtml = '';

if (theMessage.indexOf('/chatNews') == 0) {

rowHtml = this._message.buildChatNewsMessage(theMessage);
this._box.addChatNewsItem(rowHtml);

} else {


if (theMessage.indexOf('/quickjackpot') == 0) {


rowHtml = this._message.buildJackpotStreamedMessage(theMessage, 'quick');

} else if (theMessage.indexOf('/extrajackpot') == 0) {

rowHtml = this._message.buildJackpotStreamedMessage(theMessage, 'extra');

} else if (theMessage.indexOf('/superjackpot') == 0) {

rowHtml = this._message.buildJackpotStreamedMessage(theMessage, 'super');

} else if (theMessage.indexOf('/bank') == 0) {

rowHtml = this._message.buildBankStreamedMessage(theMessage);

} else if (theMessage.indexOf('/badge') == 0) {
theMessage = theMessage.replace('/badge ', '');
return;
}


this._box.addChatRow(rowHtml, targetRoomName);
}
}


ChatController.prototype.checkForJail = function() {

window.self.focus();

var cachedController = this;
$.getJSON('http://www.komogvind.dk/ajax/chat_ajax_jail.php', {tuid : chatVars.uid, action : 'check'}, function (callbackData) {

if (callbackData) {

if (callbackData.isInmate === true) {
cachedController._jailController.goToJail(callbackData.secondsRemaining);
} else {
cachedController._jailController.rls();
}
}
});
}


ChatController.prototype.messageFromIM = function (theMessage) {

var theRoomHandler = this._roomHandler;
var javaRoomObject = theRoomHandler.getCurrent();
var userVersion = false;

if (javaRoomObject) {
var theRoomName = javaRoomObject.getName();

if (theRoomHandler.isIMRoom(theRoomName)) {

if (userVersion) {
this._box.addChatRow(this._message.buildUserMessage(theMessage), javaSenderUserObject);
} else {
this._box.addChatRow(this._message.buildInfoMessage(theMessage), theRoomName);
}
}
}
}


ChatController.prototype.serverTimeout = function (type, timeout) {
var type = (type == 'restart' ? 'restart' : 'shutdown');



var time = parseInt(timeout);
var totalseconds= Math.floor((timeout + 500) / 1000);
var minutes = Math.floor(totalseconds / 60);
var seconds = totalseconds % 60;
var timestring = "";
if (minutes > 0) {
timestring = minutes + " minut" + (minutes > 1 ? "ter" : "");
timestring += " og " + seconds + " sekund" + (seconds > 1 ? "er" : "");
} else {
timestring = seconds + " sekund" + (seconds > 1 ? "er" : "");
}



var theMessage = (type == 'restart' ? "Serveren genstartes om " : "Serveren lukker ned om ") + timestring;
var targetJavaRoomObject = (this._roomHandler.multiplayerTableRoomJoined() ? this._roomHandler.getCurrentTableRoom() : this._roomHandler.getCurrent());

this._box.addChatRow(this._message.buildInfoMessage(theMessage), targetJavaRoomObject.getName());
}


ChatController.prototype.sendTypedMessage = function () {

var theBox = this._box;
var messageObject = this._message;

var theTextarea = theBox.textAreaElem;
var theMessage = jQuery.trim(theTextarea.val());

var ownChatUserObject = this._userHandler.getCurrent()._chatUserObject;
var maxMessageSize = chatSettings.getMaxMessageSize();
var roomName = this._roomHandler.getCurrentlyViewedRoomName();


var youCantSend = (!ownChatUserObject.isVip() && !(chatVars.imOtherIsAdmin));
var otherGuyCantReply = (!(chatVars.imOtherIsVip) && !(ownChatUserObject.isVisibleAdm() || ownChatUserObject.isStaff()));

if (chatSettings.isInstantMessenger() && (youCantSend || otherGuyCantReply)) {

if (youCantSend) {


var theMessage = '<a href="http://www.komogvind.dk/vip_features.php" target="_blank">' + "For at kunne sende direkte beskeder skal du være VIP. Læs mere om VIP og de fordele du kan opnå og skift til VIP allerede i dag! Klik her og læs mere!</a>";
theBox.addChatRow(messageObject.buildInfoMessage(theMessage), roomName);
return;

} else if (otherGuyCantReply) {


var theMessage = "Bemærk, din besked blev modtaget, men da brugeren ikke er VIP kan han/hun ikke svare.";
theBox.addChatRow(messageObject.buildInfoMessage(theMessage), roomName);
}


} else {


if (theMessage.length > maxMessageSize) {

var theMessage = "Din besked er for lang. Den må højest fylde " + maxMessageSize + " tegn, men fylder lige nu " + theMessage.length + '.';
theBox.addChatRow(messageObject.buildInfoMessage(theMessage), roomName);


} else if (chatSettings.chattingAllowed() && messageObject.isValid(theMessage) && !messageObject.outgoingMessagesBlocked() && !messageObject.isSpamming()) {


theBox.resetTypedMessage();


if (messageObject.isTextCommand(theMessage)) {

var targetUsername;


if ( messageObject.isIgnoreCommand(theMessage) ) {

targetUsername = messageObject.extractUsername(theMessage, 'ignore');
if (targetUsername) {
this.handleIgnore(targetUsername);
}


} else if ( messageObject.isKickCommand(theMessage) && (ownChatUserObject.isStaff() || ownChatUserObject.isKickAdm()) ) {

targetUsername = messageObject.extractUsername(theMessage, 'kick');
if (targetUsername) {
this.handleKick(targetUsername);
}


} else if ( messageObject.isMuteCommand(theMessage) && (ownChatUserObject.isStaff() || ownChatUserObject.isMuteAdm())) {

targetUsername = messageObject.extractUsername(theMessage, 'mute');
if (targetUsername) {
this.handleMute(targetUsername);
}


} else if ( messageObject.isBanCommand(theMessage) && (ownChatUserObject.isStaff() || ownChatUserObject.isBanAdm())) {

targetUsername = messageObject.extractUsername(theMessage, 'ban');
if (targetUsername) {
this.handleBan(targetUsername);
}


} else if ( messageObject.isJailCommand(theMessage) && (ownChatUserObject.isStaff() || ownChatUserObject.isBanAdm())) {

targetUsername = messageObject.extractUsername(theMessage, 'jail');
if (targetUsername) {
this.handleIncarceration(targetUsername);
}
}
}


var cleanMessage = theMessage.replace(/(<([^>]+)>)/ig, '');


cleanMessage = messageObject._wordwrap(cleanMessage);


cleanMessage = this._smileyHandler.swapSmileyPlaceholders(cleanMessage);

if (cleanMessage.length > 0) {


cleanMessage = messageObject.filterBadWords(cleanMessage);


this._server.sendOutgoingMessage(cleanMessage, roomName);
messageObject.blockOutgoingMessages();


if (chatSettings.isInstantMessenger()) {

var senderUsername = ownChatUserObject.getName();
if (chatVars.usingIMApplet && imChatController) {

var imControl = imChatController;


if (this._roomHandler.currentChatterIsAlone() && imControl && imControl.isIMAuthenticated()) {

var receiverUsername = imControl.deriveReceiverUsername(roomName, senderUsername);

var rowHtml = this.drawIncomingMessage(cleanMessage, ownChatUserObject._javaUserObject, true);
if (rowHtml != false) {
imControl.cacheTypedMessage(receiverUsername, senderUsername, cleanMessage, rowHtml, roomName);
imControl.sendInvitation(receiverUsername, senderUsername, roomName);
}
}
}
}
}


} else {
theBox.setTypedMessage(jQuery.trim(theMessage));

if (messageObject.outgoingMessagesDenied()) {
this._box.addChatRow(this._message.buildInfoMessage("Du har skrevet for mange beskeder for hurtigt. Prøv venligst igen om lidt."), roomName);
}
}
}

theBox.hideSmileyContainer();
theBox.hideStuffContainer();


theTextarea.focus();
theTextarea = null;
}


ChatController.prototype.invitation = function (senderUserObject, privateRoomName) {


if (!this.isLoggedOut() && !this._userHandler.getCurrent().ignoresUser(senderUserObject.getName())) {

this.beginPrivateChat(senderUserObject.getName(), privateRoomName);
this._box.addChatRow(this._message.buildInfoMessage(senderUserObject.getName() + " har inviteret dig til en privat chat "), privateRoomName);
}
}


ChatController.prototype.addGameAIMessage = function (type, senderName, message) {

var theRoomObject = this._roomHandler.getCurrentlyViewedRoom();
if (theRoomObject) {

switch (type) {

case 1:
var theMessage = this._message.buildAIPlayerMessage(senderName, message);
break;

case 0:
default:
var theMessage = this._message.buildAIRedboxMessage(message);
break;
}

this._box.addChatRow(theMessage, theRoomObject.getName());
}
}


ChatController.prototype.cycleEnteredUsername = function () {

var theBox = this._box;

var candidate = '';
var theTextarea = theBox.textAreaElem;
var currentMessage = theTextarea.val();

var caretPosition = theTextarea.caret();
if (caretPosition == undefined) {
caretPosition = 0;
}




var startSearchPos = caretPosition - 1;
var spacePos = currentMessage.lastIndexOf(' ', startSearchPos);

if (spacePos < 0) {
spacePos = 0;
} else if (spacePos > 0) {
spacePos++;
}

var currentWord = currentMessage.substring(spacePos, caretPosition);




if (this._userHandler.isTabUserListEmpty()) {


this._userHandler.buildTabUserList(currentWord);
}


var candidates = this._userHandler.getTabUserList();
var selectedCandidate = '';



if (candidates.length) {
selectedCandidate = candidates[this.tabUsernameCycleIndex++];


if (selectedCandidate == undefined) {
this.tabUsernameCycleIndex = 0;
selectedCandidate = candidates[this.tabUsernameCycleIndex++];
}
}


window.self.setTimeout(function(){
theTextarea.focus();
}, 0);


if (selectedCandidate.length) {

var firstPart = currentMessage.substring(0, spacePos) + selectedCandidate;
var lastPart = currentMessage.substring(caretPosition, currentMessage.length);

theBox.setTypedMessage(firstPart + lastPart);


window.self.setTimeout(function() {

theTextarea.caret(firstPart.length);
theTextarea = null;

}, 0);
}

currentMessage = null;
}


ChatController.prototype.finishEnteredUsername = function () {

var theBox = this._box;
var theTextarea = theBox.textAreaElem;
var currentMessage = theTextarea.val();

var caretPosition = theTextarea.caret();
if (caretPosition == undefined) {
caretPosition = 0;
}

var posOfNextSpace = currentMessage.indexOf(' ', caretPosition);
if (posOfNextSpace == -1) {
posOfNextSpace = currentMessage.length;
}
theTextarea.caret(posOfNextSpace);

theTextarea = null;
currentMessage = null;
}




ChatController.prototype.flushEnteredUsername = function () {
this._userHandler.flushTabUserList();
}




ChatController.prototype.drawRoomRows = function () {

if (!this._userHandler.getCurrent().isInJail()) {
var replacements = this._roomHandler.drawAllActive();
this._box.replaceRooms(replacements);

replacements = null;
}
}


ChatController.prototype.roomOnlineCount = function (roomObject, noOfChatters) {
var theRoomHandler = this._roomHandler;


theRoomHandler.replacePersistentRoom(roomObject, noOfChatters);


if (theRoomHandler.minimumRoomsRetrieved()) {

theRoomHandler.blockRoomlistRedraw();


clearTimeout(this._roomrows_draw_timer);
this._roomrows_draw_timer = window.self.setTimeout(function(){chatController.drawRoomRows();}, this._ROOMS_DRAW_DELAY_TIME);
}
}


ChatController.prototype.persistentRoomRemoved = function (javaRoomObject) {

if (javaRoomObject) {
var theRoomHandler = this._roomHandler;
theRoomHandler.removeRoom(javaRoomObject.getName());
}
}




ChatController.prototype.addMultiplayerProfileInfo = function (javaProfileInfoUserObject) {

if (javaProfileInfoUserObject) {


var profileInfoUser = new ChatProfileInfoUser(javaProfileInfoUserObject);
this._userHandler.addProfileInfoUser(profileInfoUser);


if (this._roomHandler.multiplayerTableRoomJoined()) {
this.replaceMultiplayerUserlist();
}

}
}


ChatController.prototype.tableJoined = function (javaSimpleTableObject, previouslySavedRoomName) {
if (javaSimpleTableObject || previouslySavedRoomName) {

var ownUser = this._userHandler.getCurrent();
if (ownUser) {


if (!previouslySavedRoomName) {

var currentRoomName = chatVars.defaultRoomName;
var uniqueTableName = eval('javaSimpleTableObject.' + chatVars.funcGetTableName + '()');

var serveruniqueRoomName = currentRoomName + ':' + uniqueTableName;

} else {
var serveruniqueRoomName = previouslySavedRoomName;
}


if (!ownUser.isInJail() && !this.isLoggedOut() && serveruniqueRoomName) {

var theRoomHandler = this._roomHandler;


var javaRoomObject = theRoomHandler.getCurrent();
if (javaRoomObject) {

var roomName = javaRoomObject.getName();
this._server.leaveRoom(roomName);


if (theRoomHandler.isJailRoom()) {


theRoomHandler.flushCurrent();
}
}


this._server.enterRoom(serveruniqueRoomName);
}


if (serveruniqueRoomName) {
this.setRoomNameLeft(serveruniqueRoomName);
}
}

} else {
this._sendError('tableJoined(' + javaSimpleTableObject + ') :: javaSimpleTableObject is not an object! :: type: ' + typeof(javaSimpleTableObject));
}
}

ChatController.prototype.tableLeft = function (javaSimpleTableObject) {



var theRoomHandler = this._roomHandler;


var theTable = theRoomHandler.getCurrentTableRoom();
if (theTable) {

this._server.leaveRoom(theTable.getName());
theRoomHandler.flushCurrentTableRoom();
this.hideMultiplayerUserlist();


var ownUser = this._userHandler.getCurrent();
if (ownUser && !ownUser.isInJail() && !this.isLoggedOut()) {


this._server.enterRoom(chatVars.defaultRoomName);
}
}
this.setRoomNameLeft(null);
}




ChatController.prototype._sendError = function(dump, ignoreLimiter) {

var isRightUser = (chatVars.mbp == 'ThorupJensen' || chatVars.mbp == 'duroflex');


if (isRightUser && this._email_errors && document.chatApplet) {


var version = document.chatApplet.getSystemProperty("java.version");
var vendor = document.chatApplet.getSystemProperty("java.vendor");
var browser_type = navigator.appName;
var browser_version = navigator.appVersion;

var getString = "http://www.komogvind.dk/chat/error.php?dump=EXCEPTION: " + dump + ":BROWSER_TYPE:" + browser_type + ":BROWSER_NAME:" + browser_version;

ignoreLimiter = true;
if (ignoreLimiter != undefined) {
getString += '&ignoreLimiter=1';
}

$.get(getString);
}

}



var chatTools;
var chatSettings;
var chatController;
var imChatController;

var chatStarted = false;





function initStart() {
$(document).ready(function() {


if (!chatStarted ) {
chatStarted = true;

chatTools = new ChatTools();
chatSettings = new ChatSettings();
chatController = new ChatController();
imChatController = new IMChatController();


if (chatController._box.chatBoxElem.length) {


window.self.setTimeout(function(){chatController.connect()}, 5000);
}


imInitStart();
}
});
}


function reStart() {

window.self.location.reload();

}


function connectSuccess() {
if (chatController) {
chatController.authenticate();
}
}


function connectFailure(host, port) {
if (chatController) {
chatController.connectFailure(host, port);
}
}


function connectionClosed() {
if (chatController) {
chatController.connectionClosed();
}
}


function dontReconnect() {
if (chatController) {
chatController.closeConnection();
}
}


function loginSuccess(javaUserObject) {

if (typeof(javaUserObject) != 'object') {
//reStart();
} else if (chatController) {
chatController.loginSuccess(javaUserObject);
} else {
//reStart();
}
}


function loginError(errorNumber) {
if (chatController) {
chatController.loginError(errorNumber);
}
}


function roomJoined(javaRoomObject) {
if (chatController) {
chatController.roomJoined(javaRoomObject);
}
}


function chatterJoined(javaRoomObject, javaUserObject) {
if (chatController) {
chatController.chatterJoined(javaRoomObject, javaUserObject);
}
}


function chatterLeft(javaRoomObject, javaUserObject) {
if (chatController) {
chatController.chatterLeft(javaRoomObject, javaUserObject);
}
}


function roomOnlineCount(javaRoomObject, numberOfChatters) {
if (chatController) {
chatController.roomOnlineCount(javaRoomObject, numberOfChatters);
}
}


function persistentRoomRemoved(javaRoomObject) {
if (chatController) {
chatController.persistentRoomRemoved(javaRoomObject);
}
}


function incomingMessage(message, targetJavaRoomObject, senderJavaUserObject) {
if (chatController) {


var rowHtml = chatController.drawIncomingMessage(message, senderJavaUserObject);
if (rowHtml != false) {

var globalChatboxCopy = chatController._box;
var theRoomName = targetJavaRoomObject.getName();

globalChatboxCopy.addChatRow(rowHtml, theRoomName);



if (chatSettings.isInstantMessenger()) {
if (globalChatboxCopy._imWindowBlurred && imChatController && senderJavaUserObject.getName() != chatVars.mbp) {
imChatController.blinkIMWindowTitle(theRoomName);
imChatController.playNewMsgSound(theRoomName);
}
}
}
}
}


function incomingStreamMessage(message, targetJavaRoomObject) {
if (chatController && targetJavaRoomObject) {
chatController.incomingStreamMessage(message, targetJavaRoomObject.getName());
}
}


function invitation(senderJavaUserObject, privateRoomName) {
if (chatController) {
chatController.invitation(senderJavaUserObject, privateRoomName);
}
}



function userSettingChanged (affectedJavaUserObject, key) {

switch (key) {

case 'chosenChatIconID':
chatController.setChatIconID(affectedJavaUserObject);
break;
default:
break;
}
}

function userSettingRemoved (affectedJavaUserObject, key) {}

function userSettingChangeDenied (key) {}






function tableJoined (javaSimpleTableObject) {
if (chatController) {
chatController.tableJoined(javaSimpleTableObject);
}
}

function tableLeft (javaSimpleTableObject) {
if (chatController) {
chatController.tableLeft(javaSimpleTableObject);
}
}


function userProfileBuilder (javaProfileInfoUserObject) {
if (chatController) {
chatController.addMultiplayerProfileInfo(javaProfileInfoUserObject);
}
}


function serverRestart(timeout) {
if (chatController) {
chatController.serverTimeout('restart', timeout);
}
}

function serverShutdown(timeout) {
if (chatController) {
chatController.serverTimeout('shutdown', timeout);
}
}


function messageFromGame(type, senderName, message) {
if (chatController) {
chatController.addGameAIMessage(type, senderName, message);
}
}






function imInitStart() {
$(document).ready(function () {

var failCounter = 10;

try {


window.setTimeout(function(){imChatController.connectToIM();}, 1000);

} catch(e) {

if (--failCounter > 0) {
window.setTimeout(imInitStart, 3000);
}
}
});
}


function imUDPConnectFailed() {
imChatController.connectionFailed(1);
}


function imTCPConnectFailed() {
imChatController.connectionFailed(2);
}


function imConnectSuccess() {
imChatController.connectionSuccess();
}



function imMediumClosed() {
if (!imChatController) {
var imChatController = new IMChatController();
}
imChatController.connectionFailed(3);
}



function imLoginFailed(reason) {
imChatController.imLoginFailed(reason);
}



function imLoginSuccess(javaUserObject) {
imChatController.loginSuccess(javaUserObject);



if (chatVars.showPopup) {



imChatController.checkForCachedMessages(javaUserObject.getName());


window.self.setInterval(function () {
imChatController.checkForCachedMessages(javaUserObject.getName());
}, 3600000);

window.self.setInterval(function () {
imChatController.showIMsPending();
}, 6500);
}
}


function imInvitationDelivered (username, roomname) {
imChatController.imInvitationDelivered(username, roomname);
}



function imInviteFailed(username, reason) {
imChatController.imInvitationFailed(username, reason);
}



function imInvitationReceived (sendingJavaUserObject, roomName) {
imChatController.addToIMsPending(sendingJavaUserObject, roomName);
}


function imInvitationAccepted (userName, roomName) {
imChatController.imInvitationAccepted(userName, roomName);
}


function imInvitationCanceled(username, roomname, reason) {


if (reason != 2) {
imChatController.imInvitationCanceled(username, roomname, reason);
}
}


function imInvitationDeclined (userName, roomName) {
imChatController.imInvitationDeclined(userName, roomName);
}


function imUserLookup(sendingJavaUserObject) {


imChatController.checkForEventListener('imLookupUserByName', sendingJavaUserObject);
}










ChatSmiley.prototype._chars;
ChatSmiley.prototype._dir;
ChatSmiley.prototype._filename;
ChatSmiley.prototype._imageObject;
ChatSmiley.prototype._vipOnly;
ChatSmiley.prototype._nickname;
ChatSmiley.prototype._html;


function ChatSmiley(typeSetting, chars, filename, vipOnly, nickname) {
this._chars = chars;
this._encodedChars = chatTools._encodeString(this._chars);

this._dir = ((typeSetting == 'static' && filename.indexOf('stu_') == -1) ? 'static' : 'animated');
this._filename = filename;
this._vipOnly = vipOnly;
this._nickname = nickname;

this.remakePublicHtml();
}


ChatSmiley.prototype.getDir = function () {
return this._dir;
}

ChatSmiley.prototype.getChars = function () {
return this._chars;
}

ChatSmiley.prototype.getEncodedChars = function () {
return this._encodedChars;
}

ChatSmiley.prototype.getNickname = function () {
return this._nickname;
}

ChatSmiley.prototype.isVIPOnly = function() {
return this._vipOnly;
}


ChatSmiley.prototype.getFilename = function (greyVersion) {

if (greyVersion) {


var greyFilename = this._filename.replace('.gif', '_grey.gif');
return greyFilename;
}
return this._filename;
}


ChatSmiley.prototype.remakePublicHtml = function (typeSetting) {

this._dir = ((typeSetting == 'static' && this.getFilename().indexOf('stu_') == -1) ? 'static' : 'animated');

var smileyStrAr = new Array('<img src="/images/smileys/', this.getDir(), '/', this.getFilename(), '" alt="smiley" align="absmiddle" />');
this._html = smileyStrAr.join('');
}
ChatSmiley.prototype.getHtml = function () {
return this._html;
}








ChatSmileyHandler.prototype._smileys = new Array();
ChatSmileyHandler.prototype._smileyCounter = 100;




ChatSmileyHandler.prototype.drawStuffBoxes = function () {
return this.smileyBoxesGenerator('stuff');
}


ChatSmileyHandler.prototype.drawSmileyBoxes = function () {
return this.smileyBoxesGenerator('smiley');
}


ChatSmileyHandler.prototype.remakeSmileyHtml = function (typeSetting) {
var smileys = this.getAllSmileys();
if (smileys != false) {

for (var nickname in smileys) {
var theSmiley = this.getSmiley(nickname);
theSmiley.remakePublicHtml(typeSetting);
}
}
}


ChatSmileyHandler.prototype.smileyBoxesGenerator = function (category) {

var cachedController = chatController;
var ownUserObject = cachedController._userHandler.getCurrent()._chatUserObject;
var type = chatSettings.getSmileyType();

var categoryWord = (category == 'stuff' ? 'stuff' : 'smiley');

var pageHtml = '';

var stringArray = new Array();

var smileys = this.getAllSmileys();
for (var nickname in smileys) {

var smileyObject = this.getSmiley(nickname);
if (smileyObject != false) {

var greyVersion = false;
if (smileyObject.isVIPOnly() && !ownUserObject.isVip()) {
greyVersion = true;
}

var smileyFilename = smileyObject.getFilename(greyVersion);
if (smileyFilename.indexOf(categoryWord) == 0) {

var smileyDir = smileyObject.getDir();
var smileyNickname = smileyObject.getNickname();
stringArray[stringArray.length] = '<img alt="' + smileyNickname + '" class="smiley" src="/images/smileys/' + smileyDir + '/' + smileyFilename + '" />';
}
}
}

stringArray[++stringArray.length] = '<div style="clear:both"></div>';
return stringArray.join('');
}


ChatSmileyHandler.prototype.getSmileyClicked = function (nickname) {
return this.getSmiley(nickname);
}


ChatSmileyHandler.prototype._addSmiley = function (typeSetting, chars, filename, vipOnly, nickname) {

var nickname = '¿' + this._smileyCounter++;
this._smileys[nickname] = new ChatSmiley(typeSetting, chars, filename, vipOnly, nickname);
}

ChatSmileyHandler.prototype.getSmiley = function (nickname) {
return this._smileys[nickname];
}

ChatSmileyHandler.prototype.getAllSmileys = function () {
return this._smileys;
}



ChatSmileyHandler.prototype.swapSmileyPlaceholders = function (theMessage, backToSmileyChars) {

if (backToSmileyChars) {

var typeSetting = chatSettings.getSmileyType();

var smileyPositions = theMessage.split('¿');
var length = smileyPositions.length;
for (var index = 0 ; index < length ; index++) {


var chunk = smileyPositions[index];
if (index > 0) {

var smileyNickname =  '¿' + chunk.substr(0, 3);
var smiley = this.getSmiley(smileyNickname);

if (smiley != undefined) {
var smileyHtml = (typeSetting == 'text' ? smiley.getChars() : smiley.getHtml());
smileyPositions[index] = smileyHtml + chunk.substr(3);
}
}
}
theMessage = smileyPositions.join('');



} else {



var selfIsVip = chatVars.selfIsVip;
var maxSmileyCap = 5;
var maxSmileyCount = 0;

var smileys = this.getAllSmileys();
for (var nickname in smileys) {

var theSmiley = this.getSmiley(nickname);

if (theSmiley.isVIPOnly() && !selfIsVip) {
continue;
} else {

var smileyChars = theSmiley.getChars();
var changedMessage = theMessage;

while (changedMessage.indexOf(smileyChars) != -1) {

if (maxSmileyCount >= maxSmileyCap) {

changedMessage = changedMessage.replace(smileyChars, '');
theMessage = changedMessage;

} else {

changedMessage = changedMessage.replace(smileyChars, theSmiley.getNickname());

if (changedMessage != theMessage) {
maxSmileyCount++;
theMessage = changedMessage;
}
}
}
}
}
}
return theMessage;
}




function ChatSmileyHandler() {

var typeSetting = chatSettings.getSmileyType();

this._addSmiley(typeSetting,':-)','smiley_smile_ani.gif', false, 'Smiling');

this._addSmiley(typeSetting,':-D','smiley_bigsmile_ani.gif',false, 'Smiling big');
this._addSmiley(typeSetting,':-O','smiley_frightened_ani.gif',false, 'Frightened');
this._addSmiley(typeSetting,':-P','smiley_tongue_ani.gif',false, 'Tongue');
this._addSmiley(typeSetting,';-)','smiley_wink_ani.gif',false, 'Winking');
this._addSmiley(typeSetting,':-(','smiley_unhappy_ani.gif',false, 'Unhappy');
this._addSmiley(typeSetting,':-S','smiley_discomfort_ani.gif',false, 'Discomfort');
this._addSmiley(typeSetting,':-|','smiley_stunned_ani.gif',false, 'Stunned');
this._addSmiley(typeSetting,':`(','smiley_crying_ani.gif',false, 'Crying');
this._addSmiley(typeSetting,':-$','smiley_shy_ani.gif',false, 'Shy');
this._addSmiley(typeSetting,'(h)','smiley_cool_ani.gif',false, 'Cool');
this._addSmiley(typeSetting,':-@','smiley_angry_ani.gif',false, 'Angry');
this._addSmiley(typeSetting,':-#','smiley_mute_ani.gif',false, 'Mute');
this._addSmiley(typeSetting,'8o|','smiley_rage_ani.gif',false, 'Rage');
this._addSmiley(typeSetting,'+o(','smiley_puke_ani.gif',false, 'Puking');
this._addSmiley(typeSetting,':-/','smiley_thinking_ani.gif',false, 'Thinking');
this._addSmiley(typeSetting,'<:)','smiley_party_ani.gif',false, 'Party');
this._addSmiley(typeSetting,'8-|','smiley_nerd_ani.gif',false, 'Nerd');
this._addSmiley(typeSetting,'*-)','smiley_wondering_ani.gif',false, 'Wondering');
this._addSmiley(typeSetting,'8-)','smiley_looking_ani.gif',false, 'Looking');
this._addSmiley(typeSetting,'|-0','smiley_sleepy_ani.gif',false, 'Sleepy');
this._addSmiley(typeSetting,'(A)','smiley_angel_ani.gif',false, 'Angel');
this._addSmiley(typeSetting,'(hh)','smiley_cool2_ani.gif',true, 'Cool2');
this._addSmiley(typeSetting,'8|D','smiley_loon_ani.gif',true, 'Loon');
this._addSmiley(typeSetting,'|-H','smiley_yelling_ani.gif',true, 'Yelling');
this._addSmiley(typeSetting,'|-)','smiley_ninja_ani.gif',true, 'Ninja');
this._addSmiley(typeSetting,'.-)','smiley_pirate_ani.gif',true, 'Pirate');
this._addSmiley(typeSetting,'v-|','smiley_sad_ani.gif',true, 'Sad');
this._addSmiley(typeSetting,'o_O','smiley_wierd_ani.gif',true, 'Wierd');
this._addSmiley(typeSetting,'><|','smiley_realsad_ani.gif',true, 'Realsad');
this._addSmiley(typeSetting,'O->','smiley_alien_ani.gif',true, 'Alien');
this._addSmiley(typeSetting,':<>','smiley_duck_ani.gif',true, 'Duck');


this._addSmiley(typeSetting,'(yes)','smiley_yes_ani.gif',true, 'Yes');
this._addSmiley(typeSetting,'(no)','smiley_no_ani.gif',true, 'No');
this._addSmiley(typeSetting,'(old)','smiley_granddaddy_ani.gif',true, 'Granddaddy');
this._addSmiley(typeSetting,'(spin)','smiley_spinaround_ani.gif',true, 'Spinaround');
this._addSmiley(typeSetting,'(tmnt)','smiley_ninjaturtle_ani.gif',true, 'TNMT');


this._addSmiley(typeSetting,'(music)','smiley_musiclistning_ani.gif',true, 'Musiclistning');
this._addSmiley(typeSetting,'(hair)','smiley_hair_ani.gif',true, 'Hair');
this._addSmiley(typeSetting,'(excited)','smiley_excited_ani.gif',true, 'Excited');
this._addSmiley(typeSetting,'(hugesmile)','smiley_hugesmile_ani.gif',true, 'Hugesmile');
this._addSmiley(typeSetting,'(hugeeyes)','smiley_hugeeyes_ani.gif',true, 'Hugeeyes');


this._addSmiley(typeSetting,'(clown)','smiley_clown_ani.gif',true, 'Clown');
this._addSmiley(typeSetting,'(devil)','smiley_devil_ani.gif',true, 'Devil');
this._addSmiley(typeSetting,'(lol)','smiley_lol_ani.gif',true, 'Laughingoutloud');
this._addSmiley(typeSetting,'(sleep)','smiley_sleeping_ani.gif',true, 'Sleeping');
this._addSmiley(typeSetting,'(waving)','smiley_waving_ani.gif',true, 'Waving');


this._addSmiley(typeSetting,'(dumb)','smiley_dumb_ani.gif',true, 'DumbAss');
this._addSmiley(typeSetting,'(eyebrow)','smiley_eyebrow_ani.gif',true, 'Eyebrows');
this._addSmiley(typeSetting,'(police)','smiley_police_ani.gif',true, 'Policeman');
this._addSmiley(typeSetting,'(freeze)','smiley_freeze_ani.gif',true, 'Freezing');
this._addSmiley(typeSetting,'(zip)','smiley_zip_ani.gif',true, 'Zipit');



this._addSmiley(typeSetting,'(Y)','stuff_thumbsup_ani.gif',false, 'Thumbsup');
this._addSmiley(typeSetting,'(N)','stuff_thumbsdown_ani.gif',false, 'Thumbsdown');
this._addSmiley(typeSetting,'(yn)','stuff_fingerscrossed_ani.gif',false, 'CrossedFingers');
this._addSmiley(typeSetting,'(clap)','stuff_clapinghands_ani.gif',true, 'Clapinghands');
this._addSmiley(typeSetting,'(peace)','stuff_peacefingers_ani.gif',true, 'PeaceFingers');
this._addSmiley(typeSetting,'(point)','stuff_pointfinger_ani.gif',true, 'Pointingfinger');
this._addSmiley(typeSetting,'(wave)','stuff_wavinghand_ani.gif',true, 'Wavinghand');

this._addSmiley(typeSetting,'(L)','stuff_heart_ani.gif',false, 'Heart');
this._addSmiley(typeSetting,'(U)','stuff_heartbroken_ani.gif',false, 'Heart broken');
this._addSmiley(typeSetting,'(Z)','stuff_man_ani.gif',false, 'Man');
this._addSmiley(typeSetting,'(X)','stuff_woman_ani.gif',false, 'Woman');
this._addSmiley(typeSetting,'({)','stuff_manhug_ani.gif',false, 'Manhug');
this._addSmiley(typeSetting,'(})','stuff_womanhug_ani.gif',false, 'Womanhug');
this._addSmiley(typeSetting,'(K)','stuff_kiss_ani.gif',false, 'Kiss');

this._addSmiley(typeSetting,'(&)','stuff_dog_ani.gif',false, 'Dog');
this._addSmiley(typeSetting,'(@)','stuff_cat_ani.gif',false, 'Cat');
this._addSmiley(typeSetting,':-[','stuff_bat_ani.gif',false, 'Bat');
this._addSmiley(typeSetting,'(bah)','stuff_sheep_ani.gif',false, 'Sheep');
this._addSmiley(typeSetting,'(tu)','stuff_turtle_ani.gif',false, 'Turtle');
this._addSmiley(typeSetting,'(sn)','stuff_snail_ani.gif',false, 'Snail');
this._addSmiley(typeSetting,'(ch)','stuff_chicken_ani.gif',true, 'Chicken');

this._addSmiley(typeSetting,'(D)','stuff_drink_ani.gif',false, 'Drink');
this._addSmiley(typeSetting,'(B)','stuff_beer_ani.gif',false, 'Beer');
this._addSmiley(typeSetting,'(C)','stuff_coffee_ani.gif',false, 'Coffee');

this._addSmiley(typeSetting,'(^)','stuff_birthdaycake_ani.gif',false, 'Birthdaycake');
this._addSmiley(typeSetting,'(pi)','stuff_pizza_ani.gif',false, 'Pizza');


this._addSmiley(typeSetting,'(bu)','stuff_burger_ani.gif',true, 'Burger');
this._addSmiley(typeSetting,'(dn)','stuff_doughnut_ani.gif',true, 'Doughnut');
this._addSmiley(typeSetting,'(fr)','stuff_frenchfries_ani.gif',true, 'Frenchfries');
this._addSmiley(typeSetting,'(ic)','stuff_icecream_ani.gif',true, 'Icecream');
this._addSmiley(typeSetting,'(sd)','stuff_softdrink_ani.gif',true, 'Softdrink');

this._addSmiley(typeSetting,'(||)','stuff_bowl_ani.gif',false, 'Bowl');
this._addSmiley(typeSetting,'(pl)','stuff_plate_ani.gif',false, 'Plate');

this._addSmiley(typeSetting,'(g)','stuff_gift_ani.gif',false, 'Gift');
this._addSmiley(typeSetting,'(o)','stuff_time_ani.gif',false, 'Watch');
this._addSmiley(typeSetting,'(8)','stuff_music_ani.gif',false, 'Music');
this._addSmiley(typeSetting,'(I)','stuff_lightbulp_ani.gif',false, 'Lightbulb');
this._addSmiley(typeSetting,'(F)','stuff_rose_ani.gif',false, 'Rose');
this._addSmiley(typeSetting,'(W)','stuff_rosedying_ani.gif',false, 'Rosedead');
this._addSmiley(typeSetting,'(ci)','stuff_cigarette_ani.gif',false, 'Cigarette');
this._addSmiley(typeSetting,'(T)','stuff_telephone_ani.gif',false, 'Telephone');
this._addSmiley(typeSetting,'(mp)','stuff_mobile_ani.gif',false, 'Cellphone');
this._addSmiley(typeSetting,'(P)','stuff_camera_ani.gif',false, 'Camera');
this._addSmiley(typeSetting,'(e)','stuff_letter_ani.gif',false, 'Letter');
this._addSmiley(typeSetting,'(~)','stuff_filmscroll_ani.gif',false, 'MovieRoll');
this._addSmiley(typeSetting,'(um)','stuff_umbrella_ani.gif',false, 'Umbrella');

this._addSmiley(typeSetting,'(%)','stuff_handcuffs_ani.gif',false, 'Handcuffs');

this._addSmiley(typeSetting,'(so)','stuff_football_ani.gif',false, 'Football');
this._addSmiley(typeSetting,'(nba)','stuff_basketball_ani.gif',true, 'Basketball');
this._addSmiley(typeSetting,'(bb)','stuff_beachball_ani.gif',true, 'Beachball');

this._addSmiley(typeSetting,'(ip)','stuff_palms_ani.gif',false, 'Island');
this._addSmiley(typeSetting,'(au)','stuff_car_ani.gif',false, 'Car');
this._addSmiley(typeSetting,'(ap)','stuff_plane_ani.gif',false, 'Plane');

this._addSmiley(typeSetting,'(r)','stuff_rainbow_ani.gif',false, 'Rainbow');
this._addSmiley(typeSetting,'(st)','stuff_rain_ani.gif',false, 'Rain');
this._addSmiley(typeSetting,'(#)','stuff_sun_ani.gif',false, 'Sun');
this._addSmiley(typeSetting,'(*)','stuff_star_ani.gif',false, 'Star');
this._addSmiley(typeSetting,'(S)','stuff_moon_ani.gif',false, 'Moon');
this._addSmiley(typeSetting,'(gl)','stuff_world_ani.gif',true, 'World');

this._addSmiley(typeSetting,'(fl)','stuff_flagdk_ani.gif',true, 'Flag');

this._addSmiley(typeSetting,'(d1)','stuff_dice1_ani.gif',true, 'Dice1');
this._addSmiley(typeSetting,'(d2)','stuff_dice2_ani.gif',true, 'Dice2');
this._addSmiley(typeSetting,'(d3)','stuff_dice3_ani.gif',true, 'Dice3');
this._addSmiley(typeSetting,'(d4)','stuff_dice4_ani.gif',true, 'Dice4');
this._addSmiley(typeSetting,'(d5)','stuff_dice5_ani.gif',true, 'Dice5');
this._addSmiley(typeSetting,'(d6)','stuff_dice6_ani.gif',true, 'Dice6');


this._addSmiley(typeSetting,'(candy)','stuff_candy_ani.gif',true, 'Candy');
this._addSmiley(typeSetting,'(chgift)','stuff_christmasgift_ani.gif',true, 'Christmas Gift');
this._addSmiley(typeSetting,'(chtree)','stuff_christmastree_ani.gif',true, 'Christmas Tree');
this._addSmiley(typeSetting,'(duck)','stuff_duck_ani.gif',true, 'Duck');
this._addSmiley(typeSetting,'(fw)','stuff_fireworks_ani.gif',true, 'Fireworks');
this._addSmiley(typeSetting,'(ice)','stuff_icecube_ani.gif',true, 'Icecube');
this._addSmiley(typeSetting,'(orange)','stuff_orange_ani.gif',true, 'Orange');
this._addSmiley(typeSetting,'(snow)','stuff_snow_ani.gif',true, 'Snow');
this._addSmiley(typeSetting,'(pin)','stuff_pinguin_ani.gif',true, 'Penguin');
this._addSmiley(typeSetting,'(santa)','stuff_santa_ani.gif',true, 'Santa');
this._addSmiley(typeSetting,'(snowman)','stuff_snowman_ani.gif',true, 'Snowman');
}







IMChatController.prototype._email_errors = true;

IMChatController.prototype.serverPorts = chatVars.imServerPorts;
IMChatController.prototype.connectInterval = 5000;

IMChatController.prototype.connected = false;
IMChatController.prototype.connectionTimer = null;
IMChatController.prototype.usingUDP = true;
IMChatController.prototype.usingTCP = false;
IMChatController.prototype.currentUDPIndex = -1;
IMChatController.prototype.currentTCPIndex = -1;

IMChatController.prototype._ownJavaUserObject = false;
IMChatController.prototype._loggedIn = false;

IMChatController.prototype._invitationDelivered = false;
IMChatController.prototype._IMsPending = new Array();
IMChatController.prototype._IMEventListeners = new Array();

IMChatController.prototype._newIMSoundPlayed = new Array();
IMChatController.prototype._newMsgSoundPlayed = new Array();
IMChatController.prototype._imMsgBlinkTimers = new Array();
IMChatController.prototype._imWindowBlurred = false;
IMChatController.prototype._imOrigTitle = '';

IMChatController.prototype._IMWindows = new Array();



function IMChatController() {}

IMChatController.prototype.connectToIM = function () {


if (!this.connected && chatVars.mbp.length && chatVars.serv.length) {


var thePort = this._getNextPort();

if (thePort != '') {

if (this.usingUDP) {
document.chatApplet.imConnectUDP(thePort);
} else if (this.usingTCP) {
document.chatApplet.imConnectTCP(thePort);
}


if (thePort != -1) {

var cachedIMController = this;
this.connectionTimer = window.setTimeout(function () {

cachedIMController.connectToIM();

}, this.connectInterval);


this.connected = true;

} else {


window.clearTimeout(this.connectionTimer);
}
} else {

}
}
}


IMChatController.prototype._getNextPort = function () {
var triedAllUDPs = ( (this.currentUDPIndex+1) == this.serverPorts.udp.length);
var triedAllTCPs = ( (this.currentTCPIndex+1) == this.serverPorts.tcp.length);

if (!triedAllUDPs) {
return this.serverPorts.udp[++this.currentUDPIndex];
}

if (!triedAllTCPs) {
this.usingUDP = false;
this.usingTCP = true;
return this.serverPorts.tcp[++this.currentTCPIndex];
}
return -1;
}

IMChatController.prototype._resetConnectParams = function () {
this.connected = false;
this.connectionTimer = null;
this.usingUDP = true;
this.usingTCP = false;
this.currentUDPIndex = -1;
this.currentTCPIndex = -1;
}


IMChatController.prototype.connectionFailed = function (reason) {




this.connected = false;

if (reason == 3) {


var imController = this;
window.setTimeout(function(){
imController._resetConnectParams();
imInitStart();
}, 5000);
}
}

IMChatController.prototype.connectionSuccess = function () {


IMChatController.prototype.currentUDPIndex = -1;
IMChatController.prototype.currentTCPIndex = -1;


document.chatApplet.imAuthenticate(chatVars.mbp, chatVars.serv);



}

IMChatController.prototype.loginSuccess = function (javaUserObject) {
this._ownJavaUserObject = javaUserObject;
this._loggedIn = true;

}


IMChatController.prototype.imLoginFailed = function (reason) {

this._sendError('IM 1.0: login failed ' + reason);


}


IMChatController.prototype.isIMAuthenticated = function () {
return document.chatApplet.isIMAuthenticated();
}

IMChatController.prototype.sendInvitation = function (receiverUsername, senderUsername, roomName) {
document.chatApplet.imInvite(receiverUsername, roomName);


}

IMChatController.prototype.imInvitationDelivered = function (username, roomname) {


this._invitationDelivered = true;


}



IMChatController.prototype.imDisplayPopup = function (sendingJavaUserObject, roomName) {

try {

var senderUsername = sendingJavaUserObject.getName();
var senderIsMale = sendingJavaUserObject.isMale();
var senderIsVip = sendingJavaUserObject.isVip();

var cachedChatVars = chatVars;
var cachedIMController = this;

if (senderUsername != undefined) {

var msgHolder = $('#msgHolder');

if (msgHolder.length) {

var myPopupWrapper = $('#chatIMPopup' + roomName, msgHolder);

if (!myPopupWrapper.length) {
msgHolder.append('<div id="chatIMPopup' + roomName + '" class="chatIMPopup"></div>');

myPopupWrapper = $('#chatIMPopup' + roomName, msgHolder);
if (myPopupWrapper.length) {

myPopupWrapper.html('<div class="themewrapper" id="ThemedBox1" style="width:280px;"><div class="outerbox" style="width:280px;"><div class="headerbar headerblue"></div><div class="headerblue_leftside"></div><div class="headerblue_rightside"></div><div class="lightborder"><div class="darkborder"><!--INNER CONTENT  - START--><div class="contentwrapper_blue innerwrapper"><div class="topgradient"></div><div id="ThemedBox1ContentWrapper"> <!--Formerly ID was "boxthemecontainer", which was no good, since many boxes may exist...--><div class="popupBody"><div class="profilePicWrapper"><div class="profilePicBorder"><img src="..." width="64" height="49" alt="" /></div><div class="profilePicBottomBorder"></div></div><div class="iconWrapper"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -109px;"></div></div></div><div class="chatIMPopupMessage textWrapper size12white"></div></div><div style="clear:both;"></div></div></div><!--INNER CONTENT  - END--><div style="clear:both;"></div></div></div><!--TABBED MENU - START--><div class="headerbar menu_blue"><div class="lefticon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -19px;"></div></div></div><div class="iconpad topmargin"><div class="popudHeader"><div class="size11white popudHeaderUsername"><strong></strong></div><div class="popupHeaderCloseIcon"><div class="iconContainer" style="width: 19px; height: 17px;"><div class="icon" style="background-position:-21px -271px;"></div></div></div><div style="clear:both;"></div></div><div style="clear:both"></div></div><!--[if IE 6]><style></style><![endif]--></div><!--TABBED MENU - END--></div></div>');





var chatIconHtml = '';
if (chatController) {
chatIconHtml = chatController._userHandler.getChatIconHtml(sendingJavaUserObject);
}
$('div.lefticon', myPopupWrapper).html(chatIconHtml);


$('div.popupHeaderCloseIcon', myPopupWrapper).unbind().click(function() {

document.chatApplet.imDeclineInvitation(sendingJavaUserObject, roomName);
myPopupWrapper.hide();



cachedIMController.removeFromIMsPending(roomName);
cachedIMController.uncacheMessages(cachedChatVars.selfUsernameUrlready, roomName);
cachedIMController.showIMsPending();
});


$('div.popudHeaderUsername > strong', myPopupWrapper).text(senderUsername);




if (chatController) {
chatController.replaceImPopupProfilePicUrl(senderUsername, myPopupWrapper);
}


var replacementText = senderUsername + " har sendt dig en direkte besked." + ' <span class="underlined">' + "Klik her</span>";
$('div.chatIMPopupMessage', myPopupWrapper).html(replacementText).unbind().click(function() {

cachedIMController.openImWindow(senderUsername, cachedChatVars.selfUsernameUrlready);
document.chatApplet.imAcceptInvitation(sendingJavaUserObject, roomName);

myPopupWrapper.slideUp(300);



cachedIMController.removeFromIMsPending(roomName);
cachedIMController.showIMsPending();
});
}
}

if (myPopupWrapper.length) {

myPopupWrapper.slideDown(1500);

}

} else {
if (chatController) {
chatController._box.showIMInviteBox(sendingJavaUserObject, senderUsername, senderIsMale, senderIsVip, roomName);
}
}
}
} catch (e) {

chatController._sendError('IM 600.0: imDisplayPopup - error name:' + e.name + ',  error message: ' + e.message);


}
}


IMChatController.prototype.openImWindow = function (senderUsername, receiverUsername) {
$(document).ready(function() {
if (chatVars.showPopup) {
senderUsername = senderUsername + '';
receiverUsername = receiverUsername + '';


var namesArray = new Array(senderUsername, receiverUsername);
namesArray.sort();

var roomname = 'IM' + namesArray[0] + namesArray[1];



var w= 510;
var h = 430;
if (screen.width) { 
var winl = (screen.width-w)/2;
var wint = (screen.height-h)/2;
} else {
winl = 0;
wint = 0;
}
if (winl < 0) {
winl = 0;
}
if (wint < 0) {
wint = 0;
}
settings = 'scrollbars = 0,resizable = 0,width=' + w + ',height=' + h + ',top=' + wint + ',left=' + winl + ',status=1';



var cachedIMController = imChatController;

if (cachedIMController._IMWindows.length) {

for (var index = 0; index < cachedIMController._IMWindows.length ; index++) {

var theWindow = cachedIMController._IMWindows[index];

if (theWindow.closed) {

theWindow = null;
break;

} else if (theWindow.name == roomname) {
break;

} else {
theWindow = null;
}
}
} else {
var theWindow = null;
}

if (theWindow == null) {
cachedIMController._IMWindows[cachedIMController._IMWindows.length] = window.self.open('/im/messenger.php?receiverid=' + receiverUsername + '&room=' + roomname + '', roomname, settings);
} else {
theWindow.focus();
}

} else {
alert("Denne service er midlertidigt lukket pga. vedligeholdelse.");
}
});
}

IMChatController.prototype.showIMsPending = function () {

if (this._IMsPending.length > 0) {

var cachedIMController = this;

var msgHolder = $('#msgHolder');
msgHolder.show();

for (var key in this._IMsPending) {

var theElem = this._IMsPending[key];
if (theElem != null && typeof(theElem) == 'object' && theElem.theUserObject && theElem.theRoomName) {

this.imDisplayPopup(theElem.theUserObject, theElem.theRoomName);
}
}


this.playNewIMSound(msgHolder);
} else {
this.resetNewIMSoundCounter();
}
}
IMChatController.prototype.removeFromIMsPending = function (roomName) {
for (var index in this._IMsPending) {
if (this._IMsPending[index] != null && this._IMsPending[index].theRoomName == roomName) {
this._IMsPending[index] = null;
}
}
}
IMChatController.prototype.addToIMsPending = function (sendingJavaUserObject, roomName) {

for (var index in this._IMsPending) {
if (this._IMsPending[index] != null && this._IMsPending[index].theRoomName == roomName) {
return;
}
}


var theObject = {theUserObject : sendingJavaUserObject, theRoomName : roomName};
this._IMsPending.unshift(theObject);
this.resetNewIMSoundCounter();
}



IMChatController.prototype.playNewIMSound = function(htmlElem) {

if (chatSettings.playIMSounds()) {

var noOfPlays = 1;

if (this._newIMSoundPlayed['roomName'] == undefined) {
this.resetNewIMSoundCounter();
}
if (this._newIMSoundPlayed['roomName'] < noOfPlays) {
this._newIMSoundPlayed['roomName']++;

var soundHtml = '<bgsound class="imPopupSound" src="/sounds/online01.wav">';
htmlElem.after(soundHtml);
}
}
}

IMChatController.prototype.resetNewIMSoundCounter = function() {
this._newIMSoundPlayed['roomName'] = 0;
}

IMChatController.prototype.playNewMsgSound = function(roomName) {
if (chatSettings.playIMSounds() && this._newMsgSoundPlayed[roomName] != true) {
this._newMsgSoundPlayed[roomName] = true;

$('html').append('<bgsound class="imPopupSound" src="/sounds/message02.wav">');
}
}
IMChatController.prototype.resetNewMsgSoundPlayed = function(roomName) {

if (chatSettings.playIMSounds()) {
this._newMsgSoundPlayed[roomName] = null;
}
}




IMChatController.prototype.blinkIMWindowTitle = function (roomName, unblink) {

if (roomName.length) {
var usableTimerKey = roomName;

if (!this._imOrigTitle.length) {
this._imOrigTitle = document.title;
}

if (unblink == true) {


var timeoutID = this._imMsgBlinkTimers[usableTimerKey];
if (timeoutID != undefined) {
window.self.clearTimeout(timeoutID);

document.title = this._imOrigTitle;
}
} else {


var timeoutID = this._imMsgBlinkTimers[usableTimerKey];
if (timeoutID != undefined) {
window.self.clearTimeout(timeoutID);
}



if (document.title == this._imOrigTitle) {
document.title = "Ny besked!";
} else {
document.title = this._imOrigTitle;
}


this._imMsgBlinkTimers[usableTimerKey] = window.self.setTimeout('imChatController.blinkIMWindowTitle("' + roomName + '")', 1000);
}
}
}



IMChatController.prototype.imInvitationAccepted = function (username, roomName) {

}


IMChatController.prototype.imInvitationCanceled = function (username, roomName, reason) {

var msgHolder = $('#chatIMPopup' + roomName);

if (msgHolder.length) {
msgHolder.slideUp(300);
}

this.removeFromIMsPending(roomName);

this.showIMsPending();
}

IMChatController.prototype.imInvitationDeclined = function (username, roomName) {




}

IMChatController.prototype.imInvitationFailed = function (username, reason) {

if (chatController) {

if (reason == 1) {
chatController.messageFromIM("Du er på modtagerens blockliste og kan derfor ikke sende.");
} else if (reason == 0) {



}
}

}





IMChatController.prototype.cacheTypedMessage = function (receiverUsername, senderUsername, cleanMessage, messageRowHtml, roomName) {

if (chatController) {

jQuery.get("/ajax/chat_ajax_msgcaching.php",
{
theSenderUsername : senderUsername,
theReceiverUsername : receiverUsername,
theRoomName : roomName,
theMessage : encodeURI(cleanMessage),
theRowHtml : encodeURI(messageRowHtml),
theAction : 'imCacheMessage',
trigger : 'ChatIMHandling'
}
);
}
}
IMChatController.prototype.uncacheMessages = function (receiverUsername, roomName) {

if (chatController) {

jQuery.get("/ajax/chat_ajax_msgcaching.php",
{
theReceiverUsername : receiverUsername,
theRoomName : roomName,
theAction : 'imUncacheMessages',
trigger : 'ChatIMHandling'
}
);
}
}


IMChatController.prototype.checkForCachedMessages = function (receiverUsername, roomName, returnMessages) {

var cachedIMController = this;
var returnMessages = (returnMessages == undefined ? false : true);

jQuery.getJSON("/ajax/chat_ajax_msgcaching.php",
{
theReceiverUsername : receiverUsername,
theRoomName : (roomName == undefined ? '' : roomName),
theAction : 'imGetCachedMessages',
flushAndGet : (returnMessages ? 1 : 0),
trigger : 'ChatIMHandling'
},


function (data) {

if (data && data.length) {

$.each(data, function(index, messageObject) {

var receiverUsername = messageObject.run;
var senderUsername = messageObject.sun;
var cleanMessage = messageObject.cm;
var rowHtml = decodeURI(messageObject.rml);
var roomName = messageObject.r;

var currentSenderUsername = '';


if (!returnMessages && currentSenderUsername != senderUsername) {
currentSenderUsername = senderUsername;



cachedIMController.registerEventListener('imLookupUserByName', currentSenderUsername, roomName);
document.chatApplet.imLookupUserByName(currentSenderUsername);


} else if (returnMessages && chatController && rowHtml.length) {


chatController._box.addChatRow(rowHtml, roomName);
}
});
}
}
);
}




IMChatController.prototype.deriveReceiverUsername = function (roomName, senderUsername) {


var receiverUsername = roomName.substr(2);


var receiverUsername = receiverUsername.replace(senderUsername, '');


return receiverUsername;
}


IMChatController.prototype._sendError = function(dump) {


if (this._email_errors) {
var version = document.chatApplet.getSystemProperty("java.version");
var vendor = document.chatApplet.getSystemProperty("java.vendor");
var browser_type = navigator.appName;
var browser_version = navigator.appVersion;

$.get("/chat/error.php?dump=EXCEPTION: " + dump + ":BROWSER_TYPE:" + browser_type + ":BROWSER_NAME:" + browser_version);
this._email_errors = false;


}
}




IMChatController.prototype.registerEventListener = function (type, uniqueIndex, data) {

if (this._IMEventListeners[type] == null) {
this._IMEventListeners[type] = new Array();
}
this._IMEventListeners[type][uniqueIndex] = data;
}


IMChatController.prototype.checkForEventListener = function () {

var type = arguments[0];

if (arguments.length && type != undefined) {

switch (type) {

case 'imLookupUserByName':

var senderJavaUserObject = arguments[1];
var roomName = this._IMEventListeners[type][senderJavaUserObject.getName()];
if (roomName) {
imChatController.addToIMsPending(senderJavaUserObject, roomName);

if (chatVars.showPopup) {
imChatController.showIMsPending();
}
}
break;
}
}
}