/*

  (c) 2006 TUFaT.com. All Rights Reserved

*/

/* document dimensions */
var docWidth = 0;
var docHeight = 0;

var appletWidth = 0;
var appletHeight = 0;

var tableConfig000 = {"border": "0", "cellSpacing": "0", "cellPadding": "0"};

var WINMINWIDTH = 360;
var WINMINHEIGHT = 240;

var POSADJX = 0;
var POSADJY = 0;

var winTypes = new Object ();
winTypes = {
  BUTTONCLOSE: 0x01,
  BUTTONMINIMIZE: 0x02,
  HASNOTITLE: 0x04,
  HASBUTTONS: 0x08
}

var actionTypes = new Object ();
actionTypes = {
  OK: 0x01,
  CANCEL: 0x02,
  DECLINE: 0x04
}

optFontChange = new Object ();

var userid_mouseover=-1;

config["effects"]= new Array ();
config["effects"]["avatarsmainchat_allow_override"]=1;
config["effects"]["avatarsmainchat"]=0;
config["effects"]["avatarsmainchat-avatar"]=":)";
config["effects"]["avatarsroomlist"]=0;
config["effects"]["avatarsroomlist_allow_override"]=1;
config["effects"]["avatarsroomlist-avatar"]=":)";
config["effects"]["showbackground"]=1;
config["effects"]["background-image"]="imgs/blank.gif";
config["effects"]["background-image-lockthemes"]=0;
config["effects"]["mypicture"]="";
config["effects"]["mypicture-temp"]="";
config["effects"]["buttonovercoloreffect"]="";
config["theme_old"]="";
config["gag"]=false;
config["gag-timeout-id"]=0;

config["messageDiv"] = new Array ();

config["role"] = new Array ();
config["role"]["ROLE_USER"] = 1;
config["role"]["ROLE_ADMIN"] = 2;
config["role"]["ROLE_MODERATOR"] = 3;
config["role"]["ROLE_SPY"] = 4;
config["role"]["ROLE_CUSTOMER"] = 8;

config["gender"] = new Array ();
config["gender"]["GENDER_MALE"] = "M";
config["gender"]["GENDER_FEMALE"] = "F";

/* options window tabs */
var optionsTabs = new Array ();
optionsTabs = ["tablabels:themes", "tablabels:text", "tablabels:effects", "tablabels:sounds", "tablabels:about"];

var skinOpts = new Array ();
skinOpts = ["background", "bodyText", "borderColor", "button", "buttonText", "buttonBorder", "dialog", "titleText", "dialogTitle", "userListBackground", "room", "roomText", "enterRoomNotify", "publicLogBackground", "privateLogBackground", "inputBoxBackground"];

var skinOptsValues  = new Array ();
var skinOptsValuesTmp  = new Array ();
for (var i in skinOpts){
	skinOptsValuesTmp[skinOpts[i]]="";
	skinOptsValues[skinOpts[i]]="";
}
skinOptsValues["enterRoomNotify"]="#ffffff";


function getATLfromBODY (node) {

  var arrayReturn = new Array ();

  var X = 0;
  var Y = 0;

  var currentNode = node;
  while ((currentNode != null) && (currentNode.tagName.toLowerCase () != "body")) {
    X += currentNode.offsetLeft;
    Y += currentNode.offsetTop;

    currentNode = currentNode.offsetParent;
  }

  arrayReturn[0] = X;
  arrayReturn[1] = Y;

  return (arrayReturn);
}

function getTLfromNode (node, fromNode) {

  var arrayReturn = new Array ();

  var X = 0;
  var Y = 0;

  var currentNode = node;
  while ((currentNode != null) && (currentNode != fromNode)) {
    X += currentNode.offsetLeft;
    Y += currentNode.offsetTop;

    currentNode = currentNode.offsetParent;
  }

  arrayReturn[0] = X;
  arrayReturn[1] = Y;

  return (arrayReturn);
}

function displayBLOCKById (id) {
  var element = document.getElementById (id);
  if (element == null)
    return;

  element.style["display"] = "block";
}

function displayNONEById (id) {
  var element = document.getElementById (id);
  if (element == null)
    return;

  element.style["display"] = "none";
}

function displayBLOCKByNode (element) {
  if (element == null)
    return;

  element.style["display"] = "block";
}

function displayNONEByNode (element) {
  if (element == null)
    return;

  element.style["display"] = "none";
}

function flushNode (node) {
  if (node == null)
    return;

  while (node.hasChildNodes ())
    node.removeChild (node.childNodes [0]);
}

function userListCompare (user1, user2) {
  var str1 = null;
  var str2 = null;

  switch (config["listOrder"]) {
    case "AZ":
      str1 = user1["login"];
      str2 = user2["login"];
      break;
    case "MOD_THEN_AZ":
      if (user1["role"] == 2 && user2["role"] != 2) return -1;
	  if (user1["role"] != 2 && user2["role"] == 2) return 1;    
      str1 = user1["login"];
      str2 = user2["login"];
      break;
    case "MOD_THEN_ENTRY":
      if (user1["role"] == 2 && user2["role"] != 2) return -1;
	  if (user1["role"] != 2 && user2["role"] == 2) return 1;    
      return 1
      break;
    case "STATUS":
      str1 = (user1["state"] > 1 ? "0" : "1");
      str2 = (user2["state"] > 1 ? "0" : "1");
      str1 += (user1["state"] > 1 ? dialogLang["statuses"][user1["state"]] : "");
      str2 += (user2["state"] > 1 ? dialogLang["statuses"][user2["state"]] : "");
      str1 += user1["login"];
      str2 += user2["login"];
      break;
    case "MOD_STATUS":
      if (user1["role"] == 2 && user2["role"] != 2) return -1;
	  if (user1["role"] != 2 && user2["role"] == 2) return 1; 
      str1 = (user1["state"] > 1 ? "0" : "1");
      str2 = (user2["state"] > 1 ? "0" : "1");
      str1 += (user1["state"] > 1 ? dialogLang["statuses"][user1["state"]] : "");
      str2 += (user2["state"] > 1 ? dialogLang["statuses"][user2["state"]] : "");
      str1 += user1["login"];
      str2 += user2["login"];
      break;
    case "ENTRY":
    	return 1;
      break;
    default:
      /* default is ENTRY */
      break;
  }
  
  str1 = String(str1).toLowerCase();
  str2 = String(str2).toLowerCase();
  
  if ((str1 == null) || (str1 < str2))
    return -1;

  if (str1 == str2)
    return 0;

  if (str1 > str2)
    return 1;
}

function ImgButton (type) {
  this.create (type);
}

ImgButton.prototype = {
  node: null,
  clickHandler: null,
  parent: null,

  create: function (type) {
    this.node = document.createElement ("img");
    this.node.setAttribute ("border", "0");
    this.node.className = "imgbutton_" + type;
    this.node.src = "themes/" + config["theme"]["name"] + "/" + config["theme"][type];
    this.node.onclick = this.onclickHandler;
    this.node.object = this;
    this.node.imgType = type;
  },

  setClickHandler: function (handler) {
    this.clickHandler = handler;
  },

  setParent: function (parent) {
    this.parent = parent;
  },

  onclickHandler: function (e) {
    var object = this.object;
    if (object.clickHandler != null)
      object.clickHandler (e);
  }
}

/* initUI */
function initUI (logoutHandler) {
	
  if (typeof (window.innerWidth) == 'number') {
    docWidth  = window.innerWidth;
    docHeight = window.innerHeight;
  }
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    docWidth = document.documentElement.clientWidth;
    docHeight = document.documentElement.clientHeight;
  }
  else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    docWidth = document.body.clientWidth;
    docHeight = document.body.clientHeight;
  }

  var AC_main = document.getElementById ("AC_main");
  appletWidth = AC_main["offsetWidth"];
  appletHeight = AC_main["offsetHeight"];
  POSADJX = AC_main["offsetLeft"];
  POSADJY = AC_main["offsetTop"];
	
  var divLayout = addDiv (AC_main, null, {"id": "layoutDiv"});

  displayNONEByNode (divLayout);

  /* preload theme images */
  var img1 = new Image ();
  img1.src = "themes/" + config["theme"]["name"] + "/" + config["theme"]["close"];
  var img2 = new Image ();
  img2.src = "themes/" + config["theme"]["name"] + "/" + config["theme"]["minimize"];
  var img3 = new Image ();
  img3.src = "themes/" + config["theme"]["name"] + "/" + config["theme"]["lock"];

  var img4 = new Image ();
  img4.src = "themes/" + config["theme"]["name"] + "/" + config["theme"]["restore"];

  config["effects"]["background-image"] = "themes/" + config["theme"]["name"] + "/" + config["theme"]["background-default"];
  ifShowBackground();
  
  /* create UI */

  var UI_row_title = addDiv (divLayout, null, {"id": "AC_mainTitleRow"});

  var UI_row_content = addDiv (divLayout, null, {"id": "AC_mainContentRow"});

  var titleTextDiv = addDiv (UI_row_title, {"padding": "2px 0 0 4px"}, null);

  var titleSpan = addSpanWText (titleTextDiv, null, null, "");
  titleSpan.langType = "lang";
  titleSpan.langStr = "welcome";

  var titleButtonDiv = addDiv (UI_row_title, {"class": "windowTitleButton"}, null);
  setElementSaP (titleButtonDiv, {"position": "absolute", "right": "2px", "top": "2px"}, null);

  var ib_close = new ImgButton ("close");
  titleButtonDiv.appendChild (ib_close.node);

  if (logoutHandler != null) {
    ib_close.setClickHandler (logoutHandler);
  }
  
  var colorPanel = createCPicker ();
  if (colorPanel != null)
    divLayout.appendChild (colorPanel);
}

function resizeWindow(){
  var chatMessages = document.getElementById ("chatMessages");
  if (chatMessages == null)
   	return;
 
  var hasToScroll = false;
  if ((config["messageDiv"]["sTopBefore"] + config["messageDiv"]["cHeightBefore"] + 5 >= config["messageDiv"]["sHeightBefore"]) || ((config["messageDiv"]["sTopBefore"] + config["messageDiv"]["cHeightBefore"] + 1 == config["messageDiv"]["sHeightBefore"]) && (config["messageDiv"]["sTopBefore"] == 0)))
  	hasToScroll = true;
  
  if (hasToScroll)
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
  var sHeight = chatMessages.scrollHeight;
  var sTop = chatMessages.scrollTop;
  var cHeight = chatMessages.clientHeight;
  config["messageDiv"]["sHeightBefore"] = sHeight;
  config["messageDiv"]["sTopBefore"] = sTop;
  config["messageDiv"]["cHeightBefore"] = cHeight;
}

function scroolMessages(){
  var chatMessages = document.getElementById ("chatMessages");
  if (chatMessages == null)
   	return;
   	
  var sHeight = chatMessages.scrollHeight;
  var sTop = chatMessages.scrollTop;
  var cHeight = chatMessages.clientHeight;
  config["messageDiv"]["sHeightBefore"] = sHeight;
  config["messageDiv"]["sTopBefore"] = sTop;
  config["messageDiv"]["cHeightBefore"] = cHeight;
}

function createUILayout (role) {	
  var layoutDiv = document.getElementById ("layoutDiv");
  if (config["itc"]["interface"] != null) {
    layoutDiv.style["fontSize"] = config["itc"]["interface"]["fontSize"] + "px";
    layoutDiv.style["fontFamily"] = config["itc"]["interface"]["fontFamily"];
    
    optFontChange["interface"] = layoutDiv;
  }

  var titleRow = document.getElementById ("AC_mainTitleRow");
  if (config["itc"]["title"] != null) {
    titleRow.style["fontSize"] = config["itc"]["title"]["fontSize"] + "px";
    titleRow.style["fontFamily"] = config["itc"]["title"]["fontFamily"];

    optFontChange["title"] = titleRow;
  }

  displayBLOCKByNode (layoutDiv);

  var rowContent = document.getElementById ("AC_mainContentRow");

  roomListMainDiv = addDiv (rowContent, null, {"id": "roomSelectRow"});
  roomListDiv = addDiv (roomListMainDiv, {"margin-top": "4px", "padding": "4px"}, null);

  var rL_select = document.createElement ("select");
  rL_select.setAttribute ("id", "roomSelect");

  var rL_room = addSpanWText (roomListDiv, null, null, "");
  rL_room.langType = "lang";
  rL_room.langStr = "room";

  roomListDiv.appendChild (document.createTextNode (" "));
  roomListDiv.appendChild (rL_select);
  roomListDiv.appendChild (document.createTextNode (" "));

  if (config["layouts"][role]["allowCreateRoom"]) {
    rL_addRoom = document.createElement ("input");
    setElementSaP (rL_addRoom, {"class": "button", "top": "0px"}, {"id": "addRoom", "type": "button"});
    rL_addRoom.langType = "lang";
    rL_addRoom.langStr = "addRoomBtn";
	rL_addRoom.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
    rL_addRoom.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
    roomListDiv.appendChild (rL_addRoom);
  }

  var chatLayout  = addDiv (rowContent, null, {"id": "chatLayout"});
  var roomList_alpha = addDiv (rowContent, null, {"id": "roomList_alpha"});
  var roomList = addDiv (rowContent, null, {"id": "roomList"});

  var chatMesgDiv = addDiv (chatLayout, null, {"id": "chatMessagesDiv"});
  var chatMessages_alpha = addDiv (chatMesgDiv, null, {"id": "chatMessages_alpha"});  
  var chatMessages = addDiv (chatMesgDiv, null, {"id": "chatMessages"});
  chatMessages.messagesNo = 0;
  window.onresize = resizeWindow;
  chatMessages.onscroll = scroolMessages;

  

  if (config["itc"]["mainChat"] != null) {
    chatMessages.style["fontSize"] = config["itc"]["mainChat"]["fontSize"] + "px";
    chatMessages.style["fontFamily"] = config["itc"]["mainChat"]["fontFamily"];

    optFontChange["mainChat"] = chatMessages;
  }


  var layoutBottomDiv = addDiv (chatLayout, null, {"id": "bottomDiv"});

  if (config["layouts"][role]["showOptionPanel"] == "1") {

    var optionsDiv = addDiv (layoutBottomDiv, null, {"id": "optionsDiv"});

    if (config["layouts"][role]["toolbar"]["status"] == "1") {
      var status_Select = document.createElement ("select");
      setElementSaP (status_Select, null, {"id": "statusSelect"});

      optionsDiv.appendChild (status_Select);
      optionsDiv.appendChild (document.createTextNode (" "));
    }

    if (config["layouts"][role]["toolbar"]["skin"] == "1") {
      var options_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button", "id": "skinBtn"});
      options_Button.langType = "lang";
      options_Button.langStr = "skinBtn";
	  options_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
      options_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
      optionsDiv.appendChild (document.createTextNode (" "));
    }
   
    if (config["layouts"][role]["toolbar"]["save"] == "1") {
      var save_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button", "id": "saveBtn"});
      save_Button.langType = "lang";
      save_Button.langStr = "saveBtn";
	  save_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
      save_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
      optionsDiv.appendChild (document.createTextNode (" "));
    }

    if (config["layouts"][role]["toolbar"]["help"] == "1") {
      var help_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button", "id": "helpBtn"});
      help_Button.langType = "lang";
      help_Button.langStr = "helpBtn";
	  help_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
      help_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
      optionsDiv.appendChild (document.createTextNode (" "));
    }

    if (config["layouts"][role]["showInputBox"] == "1") {

      if (config["layouts"][role]["toolbar"]["smilies"] != "0") {
        var smiles_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button", "id": "smilesBtn"});
        smiles_Button.value = ":)";
		smiles_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
    	smiles_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
        optionsDiv.appendChild (document.createTextNode (" "));
      }

      var bold_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button"});
      bold_Button.value = "B";
      bold_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
      bold_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
      bold_Button.onclick = function () { insertBoldItalic ("bold"); }

      optionsDiv.appendChild (document.createTextNode (" "));

      var italic_Button = addInput (optionsDiv, {"class": "button", "position": "static"}, {"type": "button"});
      italic_Button.value = "I";
      italic_Button.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
      italic_Button.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
      italic_Button.onclick = function () { insertBoldItalic ("italic"); }

      optionsDiv.appendChild (document.createTextNode (" "));
    }

    if (config["layouts"][role]["toolbar"]["color"] == "1") {
      var colorBtn = document.createElement ("input");
      setElementSaP (colorBtn, null, {"type": "button", "id": "colorBtn"});

      optionsDiv.appendChild (colorBtn);
    }
  }

  if (config["layouts"][role]["showInputBox"] == "1") {

    var inputBoxDiv = addDiv (layoutBottomDiv, null, {"id": "inputBoxDiv"});
    
    var textInputMsgDiv_alpha = addDiv (inputBoxDiv, null, {"id": "textInputMsgDiv_alpha"});    

    var textArea = document.createElement ("textarea");
    setElementSaP (textArea, {"class": "textInputMsg"}, {"id": "userTextInput","cols": "60", "maxlength": config["maxMessageSize"]});
    textArea.textStyle = new Object ();
    textArea.onkeydown = function () { ismaxlength(this); }
    
    inputBoxDiv.appendChild (textArea);
    inputBoxDiv.appendChild (document.createTextNode (" "));
    
    if (config["itc"]["mainChat"] != null) {
	    textArea.style["fontSize"] = config["itc"]["mainChat"]["fontSize"] + "px";
	    textArea.style["fontFamily"] = config["itc"]["mainChat"]["fontFamily"];
	    
	    optFontChange["inputMessage"] = textArea;
  	}
    

    var sendButton = addInput (inputBoxDiv, {"class": "button", "top": "0px"}, {"id": "sendButton", "type": "button"});
    sendButton.langType = "lang";
    sendButton.langStr = "sendBtn";
    sendButton.onmouseover = function () { this.style["backgroundColor"] = skinOptsValuesTmp["buttonover"]; }
    sendButton.onmouseout  = function () { this.style["backgroundColor"] = skinOptsValuesTmp["button"]; }
  }

   var mainNode = document.getElementById ("AC_main");
   formatUIsLanguage (mainNode, null, {"user": user["login"]});
  
   var divLayout = document.getElementById ("layoutDiv");
   var smilesWin = createSmilesWindow ();
   if (smilesWin != null)
     divLayout.appendChild (smilesWin);
   
   var color_t = new RGBColor(getStyle(document.body,"color")).toHex().replace("#","");	
   changeColor(color_t);
     
} /* end function createUILayout */

function insertBoldItalic (buttonType) {
  var textInput = document.getElementById ("userTextInput");
  if (textInput == null)
    return;

  switch (buttonType) {
    case "bold":
      if (textInput.textStyle["bolded"] != true) {
        textInput.textStyle["bolded"] = true;
        textInput.value += "<b>";
      }
      else {
        textInput.textStyle["bolded"] = false;
        textInput.value += "</b>";
      }

      break;

    case "italic":
      if (textInput.textStyle["italic"] != true) {
        textInput.textStyle["italic"] = true;
        textInput.value += "<i>";
      }
      else {
        textInput.textStyle["italic"] = false;
        textInput.value += "</i>";
      }

      break;

    default:
  }

  textInput.focus ();
}

function insertToTextInput (textToInsert) {
  var textInput = document.getElementById ("userTextInput");
  if (textInput == null)
    return;

  textInput.value += textToInsert;
}

function createContextMenu (role, forUser, handler) {
  var menuItems = new Array ();

  if (config["layouts"][role]["allowPrivateMessage"] == "1")
    menuItems.push ("privatemessage");

  if (config["layouts"][role]["allowInvite"] == "1")
    menuItems.push ("invite");

  if (config["layouts"][role]["allowFileShare"] == "1")
    menuItems.push ("fileshare");

  if (config["layouts"][role]["allowIgnore"] == "1")
    if (forUser["ignored"] != true)
      menuItems.push ("ignore");
    else
      menuItems.push ("unignore");

  if (config["layouts"][role]["allowBan"] == "1")
    menuItems.push ("ban");

  var cmDiv = document.createElement ("div");
  setElementSaP (cmDiv, {"visibility": "hidden"}, {"id": "contextMenu"});

  cmDiv.user = forUser;

  for (var i = 0; i < menuItems.length; i++) {
    var entryDiv = document.createElement ("div");
    setElementSaP (entryDiv, {"class": "cmEntry"}, null);
    entryDiv.parent = cmDiv;
    entryDiv.entry = menuItems[i];
    entryDiv.onmouseover = function () { this.className = "cmEntryOver"; }
    entryDiv.onmouseout  = function () { this.className = "cmEntry"; }
    if (handler != null)
      entryDiv.onclick = handler;

    var textSpan = addSpanWText (entryDiv, null, null, getLanguageString ("lang", menuItems[i], config["currentLanguage"], null));

    cmDiv.appendChild (entryDiv);
  }

  return (cmDiv);
} /* end of function createContextMenu */

function submitOnEnter (e) {
  if (! e)
    ev = window.event;
  else
    ev = e;

  var el = (ev.target ? ev.target : ev.srcElement);

  if (ev.keyCode)
    var keyCode = ev.keyCode;
  else if (ev.which)
    var keyCode = ev.which;

  playSound ("PressButton");

  if (keyCode == 13) {
    cancelEventPropagation (ev);
    if (el.form.handler != null)
      el.form.handler ();
  }
}

/* Window Object */
function AC_Window (mode, id, dimensions) {
  this.create (mode, id, dimensions);
}

AC_Window.prototype = {
  minimizeHandler: null,
  closeHandler: null,

  create: function (mode, id, dimensions) {
    this.windowName = id;
    this.windowFlags = mode;
    this.windowDims = dimensions;
    this.userData = new Object ();

    this.node = this.__createWindow ();
  },

  __createWindow: function () {
    if (this.node != null)
      return;

    /* create the div */
    var windowDIV = document.createElement ("div");
    windowDIV.className = "window";

    if (this.windowName != null)
      windowDIV.setAttribute ("id", this.windowName);

    var width40Percent = Math.round (appletWidth * 40 / 100);

    /* sets div's dimenstions */
    if (this.windowDims && (this.windowDims["width"] != null))
      var divWidth = this.windowDims["width"];
    else
      var divWidth = width40Percent > WINMINWIDTH ? width40Percent : WINMINWIDTH;

    var posLeft = Math.round (appletWidth / 2) - Math.round (divWidth / 2);

    setElementSaP (windowDIV, {"width": divWidth + "px", "left": posLeft + "px"}, null);

    var userForm = document.createElement ("form");
    setElementSaP (userForm, {"height": "100%"}, {"action": "javascript:;", "method": "post"});
    userForm.window = windowDIV;
    userForm["canceled"] = false;

    /* IE HACK:
      Stupid IE doesn't populate form with inputs names - ie to access them
      with formname.elements["name"] if they are created with DOM :(

      Create elems to hold the references to the input elements */

    userForm.elems = new Object ();

    windowDIV.userForm = userForm;

    var winStatus = addDiv (userForm, {"class": "windowStatusBar"}, null);

    if (! (this.windowFlags & winTypes["HASNOTITLE"])) {

      var winTitleRow = addDiv (userForm, {"class": "windowTitleRow"}, null);
      winTitleRow.setAttribute ("id",this.windowName + "winTitleRow");

      var winTitle = addDiv (winTitleRow, {"class": "windowTitle"}, null);
      winTitle.elementToDrag = windowDIV;

      if (this.windowFlags & winTypes["BUTTONCLOSE"]) {
        var cButtonDiv = addDiv (winTitleRow, {"class": "windowTitleButton"}, null);
        setElementSaP (cButtonDiv, {"position": "absolute", "top": "3px", "right": "2px"}, null);

        var button_close = new ImgButton ("close");
        button_close.setParent (this);
        button_close.setClickHandler (this.buttonCloseHandler);
        cButtonDiv.appendChild (button_close.node);
      }

      if (this.windowFlags & winTypes["BUTTONMINIMIZE"]) {
        var mButtonDiv = addDiv (winTitleRow, {"class": "windowTitleButton"}, null);
        setElementSaP (mButtonDiv, {"position": "absolute", "top": "3px", "right": "22px"}, null);

        var button_minimize = new ImgButton ("minimize");
        button_minimize.setParent (this);
        button_minimize.setClickHandler (this.buttonMinimizeHandler);
        mButtonDiv.appendChild (button_minimize.node);
      }
    }

    var winContentRow = addDiv (userForm, {"class": "windowContentRow"}, null);

    /* export this */
    windowDIV.contentData = winContentRow;

    if (this.windowFlags & winTypes.HASBUTTONS) {
      var contentButtonsRow = addDiv (winContentRow, {"class": "windowButtonsRow", "textAlign": "center"}, null);
      windowDIV.buttonsData = contentButtonsRow;
    }

    var divResize = addDiv (winStatus, {"class": "windowResizeHandler"}, null);
    divResize.elementToDrag = windowDIV;
    divResize.innerHTML = "&raquo;&nbsp;";

    windowDIV.appendChild (userForm);
    windowDIV.object = this;

    return (windowDIV);
  },

  appendToParent: function (parent) {
    /* don't show the window, yet, just layout it. If not use this, the client* attributes will have 0 value */
    this.node.style["visibility"] = "hidden";

    parent.appendChild (this.node);

    var winWidth = this.node.clientWidth;
    var winHeight = this.node.clientHeight;

    if ((this.windowDims != null) && (this.windowDims["height"] != null))
      winHeight = this.windowDims["height"];

    var posTop = Math.round (appletHeight / 2) - Math.round (winHeight / 2);
    setElementSaP (this.node, {"top": posTop + "px", "height": winHeight + "px"}, null);


    var contentDiv = this.node.contentData;
    setElementSaP (contentDiv, {"position": "absolute", "height": "auto", "bottom": "0"}, null);

    if (browserISIE ()) {
      setElementSaP (contentDiv, {"width": "100%"}, null);
      contentDiv.style.setExpression ("height", "(this.parentNode.clientHeight - 44) + \"px\"");
    }

    /* now we have the window positioned and correct layout. show it */
    this.node.style["visibility"] = "visible";

    /* TODO: change the content element to position: absolute,
      and fix the things in IE. This will help to resize */

    this.node.winWidth = winWidth;
    this.node.winHeight = winHeight;
    this.node.MINWINWIDTH = winWidth;
    this.node.MINWINHEIGHT = winHeight;
  },

  addButton: function (langType, langStr, handle, actionType) {
    if (! (this.windowFlags & winTypes.HASBUTTONS))
      return;

    var button = document.createElement ("input");
    button.setAttribute ("type", "button");

    button.className = "button";

    var caption = getLanguageString (langType, langStr, config["currentLanguage"], null);

    button.setAttribute ("value", caption);
    button.langType = langType;
    button.langStr = langStr;

    button.onclick = this.buttonAction;
    button.handler = handle;

    button.window = this.node;
    button.actionType = actionType;

    this.node.buttonsData.appendChild (button);
    return (button);
  },

  setFormHandler: function (handler) {
    this.node.userForm.handler = handler;
  },

  addContent: function (node) {
    this.node.contentData.appendChild (node);
  },

  buttonAction: function () {
    if (this.actionType == actionTypes.OK) {
      if (this.window.userForm.handler)
        this.window.userForm.handler ();
    }
    else if (this.actionType == actionTypes.DECLINE) {
      this.window.userForm["canceled"] = true;
      if (this.window.userForm.handler)
        this.window.userForm.handler ();
    }
    else
      this.window.object.closeWindow ();
  },

  buttonCloseHandler: function () {
    if (this.parent.closeHandler != null)
      this.parent.closeHandler ();
  },

  buttonMinimizeHandler: function () {
    if (this.parent.minimizeHandler != null)
      this.parent.minimizeHandler ();
  },

  setCloseHandler: function (handler) {
    this.closeHandler = handler;
  },

  setMinimizeHandler: function (handler) {
    this.minimizeHandler = handler;
  },

  closeWindow: function () {
    var parent = this.node.parentNode;
    if (parent)
    parent.removeChild (this.node);
  },

  hideWindow: function () {
    displayNONEByNode (this.node);
  },

  showWindow: function () {
    displayBLOCKByNode (this.node);
  }
}

function createPrivateWindow (user) {
  var pcWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.BUTTONMINIMIZE | winTypes.HASBUTTONS, "idWinPrivate" + user["uid"], {"width": "400"});

  var contentDoc = document.createDocumentFragment ();
  
  var textDiv = addDiv (contentDoc, {"class": "pW_textDiv"}, null);
  textDiv.setAttribute ("id", user["uid"]);
  
  var textSpan = addSpanWText (textDiv, null, null, getLanguageString ("dialog", "privateBox:toUser", config["currentLanguage"], {"user": user["login"]}));
  textSpan.langType = "dialog";
  textSpan.langStr = "privateBox:toUser";

  var messagesDiv = addDiv (contentDoc, {"class": "pW_messagesDiv"}, null);
  
  //printElement(contentDoc);
  var pwMessages = addDiv (messagesDiv, {"class": "pW_messages"}, null);
  
  
  pwMessages.setAttribute ("id", "userpwMessages" + user["uid"]);
  
  pcWin.userData["messagesDiv"] = pwMessages;
  pwMessages.messagesNo = 0;

  var inputDiv = addDiv (messagesDiv, {"class": "pW_inputDiv"}, null);
  inputDiv.setAttribute ("id", "userDivInput" + user["uid"]);

  //alert(pwMessages.parentNode.parentNode.firstChild.id);
  
  var inputBox = addInput (inputDiv, {"class": "pW_input"}, null);  
  
  pcWin.node.userForm.elems["textInput"] = inputBox;
  pcWin.userData["user"] = user;

  inputBox.onkeyup = submitOnEnter;

  /* this if fixes KHTML and Opera dimension of the input */
  if ((getBrowser () == 1) || (getBrowser () == 3)) {
    setElementSaP (inputBox, {"width": "99%"}, null);
  }

  pcWin.addButton ("dialog", "privateBox:sendBtn", null, actionTypes.OK);

  pcWin.addContent (contentDoc);
  if (! browserISIE ())
    pcWin.node.contentData.style["height"] = WINMINHEIGHT - 82 + "px";
  else
    pcWin.node.contentData.style["height"] = WINMINHEIGHT - 28 + "px";
  
  var pictureDiv = addDiv (messagesDiv, {"position": "absolute", "right": "4px"}, null);
  
  //if (user["picture"]){
	  pictureDiv.appendChild (document.createElement ("br"));
	  pictureDiv.appendChild (document.createElement ("br"));	  
	  if(document.getElementById ("userImg" + user["uid"])){
		var elem = document.getElementById ("userImg" + user["uid"]);		
		setElementSaP (elem, null, {"id": "userImg" + user["uid"]});
		elem.removeChild(this);
	  }
	  var userImg = document.createElement("img");
	  setElementSaP (userImg, null, {"id": "userImg" + user["uid"]});
	  pictureDiv.appendChild(userImg);
	  userImg.style["display"]="none";
	  if (user["picture"]){		
		userImg.src="." + user["picture"];	  	
  	  }
	  else{
		userImg.src = "";
		userImg.style["height"] = "0px";
		userImg.style["width"] = "0px";  
  	  }
	  
  	  userImg.onload = function() { setTimeout("resizePrivateWindow(" + user["uid"] + ");",500);};	
	  //if (userImg.complete)
	  setTimeout("resizePrivateWindow(" + user["uid"] + ");",200);
  //}  
  
  return (pcWin);
}

function resizePrivateWindow(iduser){
  var w,h;
  if(document.getElementById("userImg" + iduser)){
  	  userImg = document.getElementById("userImg" + iduser);
  	  userImg.style["display"] = "block";
  	  if(userImg)
  	  if (userImg.width>0){
	  	  if (userImg.width>userImg.height){
			w=160;
			h=(userImg.height*160)/userImg.width;  	
		  }else{
		  	w=(userImg.width*160)/userImg.height;
			h=160;  	
		  }		  		  
		  userImg.style["height"] = h + "px";
		  userImg.style["width"] = w + "px";  
	  }else{
		w=0;
	  	h=160;
	  }
  }else{	  	 	  
	  w=0;
	  h=160;
  }  
  if (document.getElementById("userpwMessages" + iduser))
  	document.getElementById("userpwMessages" + iduser).style["right"] = (w + 8) + "px"
  if (document.getElementById("userDivInput" + iduser))
  	document.getElementById("userDivInput" + iduser).style["right"] = (w + 8) + "px";
  if (document.getElementById("idWinPrivate" + iduser))
  	document.getElementById("idWinPrivate" + iduser).style["height"] = (h + 115) + "px";  
  //userList[iduser]["privateWin"].node.contentData.style["height"] = (h + 38) + "px";
  //pcWin.node.contentData.style["height"] = (h + 38) + "px";
}

function createInviteWindow (forUser) {

  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var roomSelect = document.getElementById ("roomSelect");
  if (! roomSelect)
    return null;

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var row = contentTable.insertRow (0);
  var cell = row.insertCell (0);

  setElementSaP (cell, {"textAlign": "right"}, {"colSpan": "2"});

  var inviteSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", "invite:inviteto", config["currentLanguage"], null));
  cell.appendChild (document.createTextNode (" "));

  var inviteRoomSelect = document.createElement ("select");
  for (var i = 0; i < roomSelect.childNodes.length; i++)
    inviteRoomSelect.appendChild (roomSelect.childNodes[i].cloneNode (true));

  cell.appendChild (inviteRoomSelect);
  newWin.node.userForm.elems["roomSelect"] = inviteRoomSelect;

  var row = contentTable.insertRow (1);
  var cell = row.insertCell (0);

  var invTextSpan = addSpanWText (cell, {"margin": "3px"}, null, getLanguageString ("dialog", "invite:includemessage", config["currentLanguage"], null));
  cell.appendChild (document.createElement ("br"));

  var textArea = document.createElement ("textarea");
  setElementSaP (textArea, {"class": "textInput", "width": "98%"}, null);

  newWin.node.userForm.elems["inviteMessage"] = textArea;

  cell.appendChild (textArea);

  contentDoc.appendChild (contentTable);

  newWin.userData["winType"] = "invite";
  newWin.userData["user"] = forUser;

  newWin.addContent (contentDoc);
  newWin.addButton ("dialog", "invite:sendBtn", null, actionTypes.OK);
  newWin.addButton ("dialog", "common:cancelBtn", null, actionTypes.CANCEL);

  return (newWin);
}

function createIgnoreWindow (forUser, ignore) {

  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var ignText = (ignore == true ? "ignore:ignoretext" : "unignore:unignoretext");
  var ignFrmText = (ignore == true ? "ignoreText" : "unignoreText");
  var ignWinType = (ignore == true ? "ignore" : "unignore");
  var ignButton = (ignore == true ? "ignore:ignoreBtn" : "unignore:unignoreBtn");

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var row = contentTable.insertRow (0);
  var cell = row.insertCell (0);

  var ignoreTextSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", ignText, config["currentLanguage"], null));
  cell.appendChild (document.createElement ("br"));

  var inputBox = addInput (cell, {"class": "textInput", "marginTop": "8px", "width": "98%"}, null);
  inputBox.onkeyup = submitOnEnter;
  newWin.node.userForm.elems[ignFrmText] = inputBox;

  contentDoc.appendChild (contentTable);

  newWin.userData["winType"] = ignWinType;
  newWin.userData["user"] = forUser;

  newWin.addContent (contentDoc);
  newWin.addButton ("dialog", ignButton, null, actionTypes.OK);

  return (newWin);
}

function createBanWindow (forUser) {

  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var roomSelect = document.getElementById ("roomSelect");

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var row = contentTable.insertRow (0);
  var cell = row.insertCell (0);

  var banTextSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", "ban:banText", config["currentLanguage"], null));
  cell.appendChild (document.createElement ("br"));

  var textArea = document.createElement ("textarea");
  setElementSaP (textArea, {"class": "textInput", "width": "98%"}, null);

  newWin.node.userForm.elems["banMessage"] = textArea;

  cell.appendChild (textArea);

  var row = contentTable.insertRow (1);
  var cell = row.insertCell (0);

  setElementSaP (cell, {"textAlign": "center"}, null);

  var radioRoom = document.createElement ("input");
  setElementSaP (radioRoom, null, {"type": "radio", "name": "banType", "checked": "checked"});
  newWin.node.userForm.elems["roomRadio"] = radioRoom;

  cell.appendChild (radioRoom);

  var rroomTextSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "ban:fromRoom", config["defaultLanguage"], null));

  cell.appendChild (document.createTextNode (" "));

  var radioChat = document.createElement ("input");
  setElementSaP (radioChat, null, {"type": "radio", "name": "banType"});
  newWin.node.userForm.elems["chatRadio"] = radioChat;

  cell.appendChild (radioChat);

  var rchatTextSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "ban:fromChat", config["defaultLanguage"], null));

  cell.appendChild (document.createTextNode (" "));

  var radioIP = document.createElement ("input");
  setElementSaP (radioIP, null, {"type": "radio", "name": "banType"});

  cell.appendChild (radioIP);

  var ripTextSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "ban:byIP", config["defaultLanguage"], null));

  if (roomSelect != null) {
    var row = contentTable.insertRow (2);
    var cell = row.insertCell (0);

    setElementSaP (cell, {"textAlign": "center"}, null);

    var banRoomSelect = document.createElement ("select");
    for (var i = 0; i < roomSelect.childNodes.length; i++)
      banRoomSelect.appendChild (roomSelect.childNodes[i].cloneNode (true));

    cell.appendChild (banRoomSelect);
    newWin.node.userForm.elems["roomSelect"] = banRoomSelect;
  }

  contentDoc.appendChild (contentTable);

  newWin.userData["winType"] = "ban";
  newWin.userData["user"] = forUser;

  newWin.addContent (contentDoc);
  newWin.addButton ("dialog", "ban:banBtn", null, actionTypes.OK);

  return (newWin);
}


function createConfirmWindow (cW_type, userData) {
  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var acceptBtn = null;
  var declineBtn = null;

  switch (cW_type) {
    case "invite":
	  newWin.userData["user"] = userData["user"];
      newWin.userData["room"] = userData["room"];
      
      newWin.userData["winType"] = "inviteCfrm";

      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var invSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", "invitenotify:userinvited", config["currentLanguage"], {"user": userData["user"]["login"], "room": userData["room"]["name"]}) + ":");

      cell.appendChild (document.createElement ("br"));
      var msgText = addSpanWText (cell, null, null, userData["textMessage"]);

      cell.appendChild (document.createElement ("br"));

      var inputBox = addInput (cell, {"class": "textInput", "marginTop": "8px", "width": "98%"}, null);
      newWin.node.userForm.elems["inviteResponse"] = inputBox;

      acceptBtn = "invitenotify:acceptBtn";
      declineBtn = "invitenotify:declineBtn";            	  
      break;

    case "fileshare":
      newWin.userData["user"] = userData["user"];
      newWin.userData["fileUrl"] = userData["fileUrl"];
      newWin.userData["winType"] = "fsCfrm";

      var fsText = userData["text"];

      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      cell.innerHTML = fsText;

      acceptBtn = "invitenotify:acceptBtn";
      declineBtn = "invitenotify:declineBtn";

    default:
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      break;
  }

  contentDoc.appendChild (contentTable);
  newWin.addContent (contentDoc);

  if (acceptBtn != null)
    newWin.addButton ("dialog", acceptBtn, null, actionTypes.OK);

  if (declineBtn != null)
    newWin.addButton ("dialog", declineBtn, null, actionTypes.DECLINE);

  return (newWin);
}

function createInformWindow (iW_type, userData) {
  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  switch (iW_type) {
    case "invitation":

      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = userData["accepted"] ? "misc:invitationaccepted" : "misc:invitationdeclined";

      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"], "room": userData["room"]["name"]}));

      break;

    case "fileshare":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = userData["accepted"] ? "misc:file_accepted" : "misc:file_declined";

      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"]}));

      break;
    
    case "gagconfirm":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = "misc:gagconfirm";		
      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"],"minutes": userData["minutes"]}));

      break;
   case "gag":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);
      var langString = "misc:gag";		
      var infoDiv = addDiv (cell, null, null)
      infoDiv.innerHTML = getLanguageString ("dialog", langString, config["currentLanguage"], {"duration": userData["duration"]});
      break;   
    
    case "ungagged":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);
      var langString = "misc:ungagged";		
      var infoDiv = addDiv (cell, null, null)
      infoDiv.innerHTML = getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"]});
      break;  
    
    case "alertconfirm":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);
      var langString = "misc:alertconfirm";		
      var infoDiv = addDiv (cell, null, null)
      infoDiv.innerHTML = getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"]});
      break;

    case "ignored":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = userData["ignored"] ? "misc:ignored" : "misc:unignored";

      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]["login"]}) + ":");
      cell.appendChild (document.createElement ("br"));

      var msgSpan = addSpanWText (cell, null, null, userData["textMessage"]);

      break;

    case "roomNotFound":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = "misc:roomnotfound";

      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"room": userData["room"]}));

      break;
      
    case "roomisfull":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);
      var langString = "misc:roomisfull";		
      var infoDiv = addDiv (cell, null, null)
      infoDiv.innerHTML = getLanguageString ("dialog", langString, config["currentLanguage"], {"room": userData["room"]});      
      break;

    case "userNotFound":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var langString = "misc:usernotfound";

      var textSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", langString, config["currentLanguage"], {"user": userData["user"]}));

      break;

    case "version":
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      var textSpan = addSpanWText (cell, null, null, "AJAX Chat v" + config["ajaxVersion"] + " on FlashChat v" + config["version"]);

      break;

    default:
      var row = contentTable.insertRow (0);
      var cell = row.insertCell (0);

      break;
  }

  contentDoc.appendChild (contentTable);
  newWin.addContent (contentDoc);

  newWin.addButton ("dialog", "common:okBtn", null, actionTypes.OK);

  return newWin;
}

function createAlertWindow (message) {
  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var row = contentTable.insertRow (0);
  var cell = row.insertCell (0);

  cell.innerHTML = message;

  contentDoc.appendChild (contentTable);
  newWin.addContent (contentDoc);

  newWin.addButton ("dialog", "common:okBtn", null, actionTypes.OK);

  return newWin;
}

function createAddRoomWindow () {
  var newWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS, null, null);

  if (! newWin)
    return null;

  newWin.userData["winType"] = "addRoom";

  var contentDoc = document.createDocumentFragment ();

  var contentTable = document.createElement ("table");
  setElementSaP (contentTable, {"width": "100%"}, {"border": "0", "cellSpacing": "0", "cellPadding": "4"});

  var row = contentTable.insertRow (0);
  var cell = row.insertCell (0);

  var enterNameSpan = addSpanWText (cell, null, null, getLanguageString ("dialog", "createroom:entername", config["defaultLanguage"], null));

  cell.appendChild (document.createElement ("br"));

  var roomNameInput = addInput (cell, {"class": "textInput", "marginTop": "8px", "width": "98%"}, null);
  roomNameInput.onkeyup = submitOnEnter;
  newWin.node.userForm.elems["roomName"] = roomNameInput;

  var row = contentTable.insertRow (1);
  var cell = row.insertCell (0);

  setElementSaP (cell, {"textAlign": "center"}, null);

  var radioPublic = document.createElement ("input");
  setElementSaP (radioPublic, null, {"type": "radio", "name": "roomType", "value": "1", "id": "radioPublicRoom"});
  newWin.node.userForm.elems["publicRadio"] = radioPublic;

  cell.appendChild (radioPublic);

  var publicTextSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "createroom:public", config["defaultLanguage"], null));

  cell.appendChild (document.createTextNode (" "));

  var radioPrivate = document.createElement ("input");
  setElementSaP (radioPrivate, null, {"type": "radio", "name": "roomType", "value": "2", "id": "radioPrivateRoom"});

  cell.appendChild (radioPrivate);

  var privateTextSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "createroom:private", config["defaultLanguage"], null));

  var row = contentTable.insertRow (2);
  var cell = row.insertCell (0);

  var enterPassSpan = addSpanWText (cell, null, null, " " + getLanguageString ("dialog", "createroom:enterpass", config["defaultLanguage"], null));

  cell.appendChild (document.createElement ("br"));

  var passInput = addInput (cell, {"class": "textInput", "marginTop": "8px", "width": "98%"}, null);
  passInput.onkeyup = submitOnEnter;
  newWin.node.userForm.elems["roomPass"] = passInput;

  contentDoc.appendChild (contentTable);
  newWin.addContent (contentDoc);

  newWin.addButton ("dialog", "createroom:createBtn", null, actionTypes.OK);

  return newWin;
}

function activateOWTab (tabs, tabLabel) {
  if (tabs == null)
    return;

  var cpDiv = document.getElementById ("colorPicker");
  if (cpDiv != null)
	cpDiv.style["visibility"] = "hidden";
    
  for (var i = 0; i < tabs.length; i++) {
    tabs[i][0].className = "optionsTab";
    if (tabs[i][1] != null)
      displayNONEByNode (tabs[i][1]);
  }

  if (tabLabel.tabId <= tabs.length) {
    tabs[tabLabel.tabId][0].className += " active";

    if (tabs[tabLabel.tabId][1] != null)
      displayBLOCKByNode (tabs[tabLabel.tabId][1]);
  }
}
/*
function waitLoadStylesheet(oldValue){
  var newValue="";
  if(document.getElementById("AC_mainTitleRow"))
  	newValue+=getStyle(document.getElementById("AC_mainTitleRow"),"background-color","backgroundColor");
  if(document.getElementById("roomList"))	
  	 newValue+= " - " + getStyle(document.getElementById("roomList"),"color");
  if(document.getElementById("roomList_alpha"))	
  	 newValue+= " - " + getStyle(document.getElementById("roomList_alpha"),"background-color","backgroundColor");
  if(document.getElementById("chatMessages"))	
  	 newValue+= " - " + getStyle(document.getElementById("chatMessages"),"color");
  if(document.getElementById("chatMessages_alpha"))	
  	 newValue+= " - " + getStyle(document.getElementById("chatMessages_alpha"),"background-color","backgroundColor");
  if(document.getElementById("textInputMsgDiv_alpha"))	
  	newValue+= " - " + getStyle(document.getElementById("textInputMsgDiv_alpha"),"background-color","backgroundColor");
  	
  if (newValue==oldValue)
  	setTimeout("waitLoadStylesheet('" + oldValue + "');", 500);
  else
  	setTimeout("setColorOptions(); applyColorChanges();", 500);  	
}*/

function changeTheme (themeId) {
  var themeStyleLink = config["themeSL"];  

  if (isNumber(themeId))
	 config["theme"] = config["themes"][themeId];
  else
  	config["theme"] = config["themes"][this.value];
  
  resetThemeColors();

  
  /*var oldValue="";
  if(document.getElementById("AC_mainTitleRow"))
  	oldValue+=getStyle(document.getElementById("AC_mainTitleRow"),"background-color","backgroundColor");
  if(document.getElementById("roomList"))	
  	 oldValue+= " - " + getStyle(document.getElementById("roomList"),"color");
  if(document.getElementById("roomList_alpha"))	
  	 oldValue+= " - " + getStyle(document.getElementById("roomList_alpha"),"background-color","backgroundColor");
  if(document.getElementById("chatMessages"))	
  	 oldValue+= " - " + getStyle(document.getElementById("chatMessages"),"color");
  if(document.getElementById("chatMessages_alpha"))	
  	 oldValue+= " - " + getStyle(document.getElementById("chatMessages_alpha"),"background-color","backgroundColor");
  if(document.getElementById("textInputMsgDiv_alpha"))	
  	 oldValue+= " - " + getStyle(document.getElementById("textInputMsgDiv_alpha"),"background-color","backgroundColor");
  	*/ 
  //alert(oldValue);
  	
  themeStyleLink.onload = function() { setColorOptions(); applyColorChanges(); /*setTimeout("setColorOptions(); applyColorChanges();",20);*/ };
  //themeStyleLink.href=config["theme"]["href"];
  setElementSaP (themeStyleLink, null, {"href": config["theme"]["href"]});
  
  //waitLoadStylesheet(oldValue);
  
  
  //var newThemeStyleLink = document.createElement ("link");
  
  /*
  newThemeStyleLink.type="text/css";
  newThemeStyleLink.rel="stylesheet";
  document.getElementsByTagName("head").item(0).appendChild(newThemeStyleLink);
  newThemeStyleLink.onload = function() { alert("here"); };
  newThemeStyleLink.onreadystatechange = function() { alert("here2"); };  
  newThemeStyleLink.href=config["theme"]["href"];*/
  
  var docImages = document.getElementsByTagName ("img");

  for (var i = 0; i < docImages.length; i++) {
    var cImg = docImages.item (i);

    if (! cImg.className.match ("imgbutton_"))
      continue;

    cImg.src = "themes/" + config["theme"]["name"] + "/" + config["theme"][cImg.imgType];
  }
 
  var allSel= document.getElementsByTagName("img");
  for (var i in allSel)
	if (allSel[i])
	if (allSel[i].className=="ballgif")
	if (allSel[i].src.search("/images/ball.gif") != -1)
 		allSel[i].src="themes/" + config["theme"]["name"] + "/images/ball.gif";
    
  if (config["effects"]["background-image-lockthemes-temp"]==0)
  	config["effects"]["background-image-temp"] = "themes/" + config["theme"]["name"] + "/" + config["theme"]["background-default"];
  ifShowBackground();  
  ////setColorOptions();
  //setTimeout("setColorOptions();",500);
  setTimeout("setColorOptions();",1000);
  setTimeout("setColorOptions();",2000);    
  setTimeout("applyColorChanges();",2300);
}

function Room_Object (rid, name, locked) {
  this.create (rid, name, locked);
}

Room_Object.prototype = { 
  create: function (rid, name, locked) {
    this.rid = rid;
    this.roomName = name;
    this.locked = locked;
    this.userclickhandler = null;
	this.users = new Array ();

    this.node = this.__createObject ();
    this.collapse ();
  },

  __createObject: function () {
    var roomDiv = document.createElement ("div");
    roomDiv.className = "room";
    roomDiv.setAttribute ("id", "room" + this.rid);
    roomDiv.object = this;
    
    var titleDiv = document.createElement ("div");
    setElementSaP (titleDiv, {"class": "roomTitle disabled"}, null);

    roomDiv.titleDiv = titleDiv;
    titleDiv.roomDiv = roomDiv;
    titleDiv.object = this;
    
    var collapseSpan = addSpanWText (titleDiv, {"class": "roomCollapse"}, null, "");
    
    var spanTitle = addSpanWText (titleDiv, null, null, languageStringFormat (config["roomTitleFormat"], {"room": this.roomName, "ucount": this.users.length}));
    
    titleDiv.titleSpan = spanTitle;

    var tspace = addSpanWText (titleDiv, null, null, " ");

    if (this.locked == true) {
      var lockImg = document.createElement ("img");
      lockImg.setAttribute ("border", "0");
      lockImg.src = "themes/" + config["theme"]["name"] + "/" + config["theme"]["lock"];

      titleDiv.appendChild (lockImg);
    }

    titleDiv.onclick = this.titleClick;

    var usersDiv = document.createElement ("div");
    setElementSaP (usersDiv, {"class": "roomUsers"}, null);

    roomDiv.usersDiv = usersDiv;

    roomDiv.appendChild (titleDiv);
    roomDiv.appendChild (usersDiv);
    return (roomDiv);
  },

  appendToParent: function (parent) {
    parent.appendChild (this.node);
  },

  titleClick: function () {
    var obj = this.object;

    if (obj.users.length == 0)
      return;

    if (obj.collapsed == false)
      obj.collapse ();
    else
      obj.expand ();
  },

  collapse: function () {
    displayNONEByNode (this.node.usersDiv);
    this.collapsed = true;
    this.node.titleDiv.firstChild.innerHTML = "<div class=\"roomCollapse\">+</div>";
    playSound ("RoomOpenClose");
  },

  expand: function () {
    displayBLOCKByNode (this.node.usersDiv);
    this.collapsed = false;
    this.node.titleDiv.firstChild.innerHTML = "<div class=\"roomCollapse\">&#150;</div>";    
    playSound ("RoomOpenClose");
  },

  __findUser: function (uid) {
    var position = -1;

    for (var i = 0; i < this.users.length, this.users[i].user["uid"] != uid; i++)
      ; /* iterate until found */
    position = i;

    return (position);
  },

  addUser: function (user, userList) {

    var position = -1; /* -1 means the user will be inserted last */

    for (i = 0; i < this.users.length; i++)
	  if (userListCompare (user, userList[this.users[i].user["uid"]]) <= 0){
        position = i;
        i = this.users.length;        
      }
    

    var userDiv = document.createElement ("div");
    userDiv.className = "roomUser";
    userDiv.onmouseover = this.userMouseOver;
    userDiv.onmouseout = this.userMouseOut;
    userDiv.style["position"] = "relative";

    if (position >= 0) {
      var refElement = this.users[position];

      this.node.usersDiv.insertBefore (userDiv, refElement);
      this.users.splice (position, 0, userDiv);
    }
    else {
      this.node.usersDiv.appendChild (userDiv);
      this.users.push (userDiv);
    }
    var av_div = addDiv(userDiv, null, null);
    
	if (user["rl_avatar"])    	
    	av_div.innerHTML= "<img class=\"ballgif\" src=\"" + doSmileyImage(user["rl_avatar"], config["smiles"]) + "\" id=\"useravatar"+ user["uid"] +"\" /> "; 
    else
    	av_div.innerHTML="<img class=\"ballgif\" src=\"themes/" + config["theme"]["name"] + "/images/ball.gif\" height=\"14px\" id=\"useravatar"+ user["uid"] +"\" /> ";
    
    var loginSpan = addSpanWText (av_div, null, null, user["login"] + " ");
    loginSpan.className = "textcolorval"; 
    if (config["itc"]["mytextcolor"])
  		loginSpan.style["color"] = "#" + top.user["color"];
    userDiv.appendChild (document.createTextNode (" "));

    if (user["state"] > 1)
      var statusText = "(" +dialogLang["statuses"][user["state"]] + ")";
    else
      var statusText = "";

    var statusSpan = addSpanWText (av_div , null, null, statusText);
    statusSpan.className = "textcolorval"; 
    if (config["itc"]["mytextcolor"])
  		statusSpan.style["color"] = "#" + top.user["color"];
    userDiv.statusSpan = statusSpan;
/*    statusSpan.langType = "dialog";
    statusSpan.langStr = "statuses";
*/
    userDiv.user = user;

    var restoreDiv = document.createElement ("div");
    setElementSaP (restoreDiv, {"position": "absolute", "top": "4px", "right": "2px"}, null);

    userDiv.restoreHandler = this.restorePrivate;

    imgRestore = new ImgButton ("restore");
    imgRestore.setParent (userDiv);
    imgRestore.setClickHandler (this.restoreHandler);

    restoreDiv.appendChild (imgRestore.node);

    displayNONEByNode (restoreDiv);

    userDiv.appendChild (restoreDiv);
    userDiv.restoreDiv = restoreDiv;
    userDiv.roomObj = this;

    userDiv.onclick = this.userclickhandler;

    var titleSpan = this.node.titleDiv.titleSpan;
    titleSpan.firstChild.nodeValue = languageStringFormat (config["roomTitleFormat"], {"room": this.roomName, "ucount": this.users.length});
    //setElementSaP (this.node.titleDiv, {"class": "roomTitle"}, null);
    this.node.titleDiv.className = "roomTitle";
    toChangeChatColors("colorBtn_roomText");

    if (user["color"] != null)
      userDiv.style["color"] = "#" + user["color"];
  },  
  
  setUserStatus: function (uid, newStatus) {
    var uIdx = this.__findUser (uid);

    var userDiv = this.users[uIdx];

    var statusSpan = userDiv.statusSpan;

    if (newStatus == 1) {
      statusSpan.firstChild.nodeValue = "";
      statusSpan.className = "textcolorval"; 
      if (config["itc"]["mytextcolor"])
  		statusSpan.style["color"] = "#" + top.user["color"];
      statusSpan.langType = null;
      statusSpan.langStr = null;
    }
    else {
      var langStr = "statuses:" + newStatus;
      var newString = getLanguageString ("dialog", langStr, config["currentLanguage"], null);
      statusSpan.firstChild.nodeValue = "(" + newString + ")";
      statusSpan.className = "textcolorval"; 
      if (config["itc"]["mytextcolor"])
  		statusSpan.style["color"] = "#" + top.user["color"];
      statusSpan.langType = "dialog";
      statusSpan.langStr = langStr;
    }
  },

  changeUserColor: function (uid, newColor) {
    var uIdx = this.__findUser (uid);

    var userDiv = this.users[uIdx];

    userDiv.style["color"] = "#" + newColor;
  },

  userMouseOver: function () {	
	if (userid_mouseover!=this.user["uid"]){
		playSound("UserMenuMouseOver");
	}
	userid_mouseover=this.user["uid"];
	
    this.className = "roomUserOver";    
  },

  userMouseOut: function () {	
	this.className = "roomUser";
  },

  removeUser: function (uid) {
    var position = -1;
    for (var i = 0; i < this.users.length, this.users[i].user["uid"] != uid; i++)
      ; /* iterate until found */
    position = i;

    if ((position >= 0) && (position < this.users.length)) {
        this.users[position].parentNode.removeChild (this.users[position]);
        this.users.splice (position, 1);
    }

    var titleSpan = this.node.titleDiv.titleSpan;
    titleSpan.firstChild.nodeValue = languageStringFormat (config["roomTitleFormat"], {"room": this.roomName, "ucount": this.users.length});
	if (this.users.length == 0) {
      //setElementSaP (this.node.titleDiv, {"class": "roomTitle disabled"}, null);
      this.node.titleDiv.className = "roomTitle disabled";
      toChangeChatColors("colorBtn_roomText");
      this.collapse ();
    }
  },

  remove: function () {
    this.node.parentNode.removeChild (this.node);
  },

  restoreHandler: function (e) {
    if (! e)
      var ev = window.event;
    else
      var ev = e;

    cancelEventPropagation (ev);

    if (this.parent.restoreHandler != null)
      this.parent.restoreHandler ();
  },

  restorePrivate: function () {
    if (this.user["privateWin"])
      this.roomObj.setUserMinimize (this.user, false);
      
    playSound ("PopupWindowOpen");
  },

  setUserMinimize: function (user, minimized) {
    var uid = user["uid"];
    var uIdx = this.__findUser (uid);

    var userDiv = this.users[uIdx];

    if (minimized == true) {
      displayBLOCKByNode (userDiv.restoreDiv);
      user["privateWin"].hideWindow ();
    }
    else {
      displayNONEByNode (userDiv.restoreDiv);
      user["privateWin"].showWindow ();
      user["privateWin"].node.userForm.elems["textInput"].focus ();
    }
  },

  setUserClickHandler: function (handler) {
    this.userclickhandler = handler;
  }
}

function createLoginUI () {
  var AC_main = document.getElementById ("AC_main");

  var dimension = null;
  if(config["login"]["width"]!="" || config["login"]["height"]!=""){
	  dimension = new Array();
	  if(config["login"]["width"]!="")
	  	dimension["width"] = config["login"]["width"];
	  if(config["login"]["height"]!="")
	  	dimension["height"] = config["login"]["height"];
  }
  var loginWin = new AC_Window (winTypes.BUTTONCLOSE | winTypes.HASBUTTONS | (config["login"]["title"] == "true" ? 0 : winTypes.HASNOTITLE), null, dimension);

  var loginDoc = document.createDocumentFragment ();

  var defaultLang = loginLangs[config["defaultLanguage"]];

  var loginTable = addTable ({"width": "95%", "margin": "8px auto 0 auto"}, tableConfig000);

  var lT_Row1 = addTableRow (loginTable.firstChild, null, null);
  var lT_Row1_td = addTableData (lT_Row1, {"padding": "4px 0 4px 0", "textAlign": config["login"]["title_label"]["align"]}, {"colSpan": "2"});

  /* login text */
  var loginSpan = document.createElement ("span");
  loginSpan.langType = "login"; loginSpan.langStr = "login";
  loginSpan.appendChild (document.createTextNode (defaultLang["login"]));
  lT_Row1_td.appendChild (loginSpan);

  var lT_Row2 = addTableRow (loginTable.firstChild, null, null);
  var lT_Row2_tdLeft = addTableData (lT_Row2, {"width": "40%", "padding": "2px", "textAlign": config["login"]["username"]["align"]}, null);
  var lT_Row2_tdRight = addTableData (lT_Row2, {"padding": "2px", "textAlign": "left"}, null);

  var usernameSpan = document.createElement ("span")
  usernameSpan.langType = "login"; usernameSpan.langStr = "username";
  usernameSpan.appendChild (document.createTextNode (defaultLang["username"]));
  lT_Row2_tdLeft.appendChild (usernameSpan);

  var userInput = document.createElement ("input");
  userInput.setAttribute ("type", config["login"]["username"]["type"]);
  userInput.setAttribute ("name", "username");
  loginWin.node.userForm.elems["username"] = userInput;
  userInput.onkeyup = submitOnEnter;
  setElementSaP (userInput, {"width": config["login"]["username"]["width"] + "px", "class": "textInput"}, null);
  lT_Row2_tdRight.appendChild (userInput);

  var lT_Row3 = addTableRow (loginTable.firstChild, null, null);
  var lT_Row3_tdLeft = addTableData (lT_Row3, {"width": "40%", "padding": "2px", "textAlign": config["login"]["password"]["align"]}, null);
  var lT_Row3_tdRight = addTableData (lT_Row3, {"padding": "2px", "textAlign": "left"}, null);

  var passwordSpan = document.createElement ("span");
  passwordSpan.langType = "login"; passwordSpan.langStr = "password";
  passwordSpan.appendChild (document.createTextNode (defaultLang["password"]));
  lT_Row3_tdLeft.appendChild (passwordSpan);

  var moderatorSpan = document.createElement ("span");
  moderatorSpan.langType = "login"; moderatorSpan.langStr = "moderator";
  setElementSaP (moderatorSpan, {"fontSize": "small"}, null);
  moderatorSpan.appendChild (document.createTextNode (defaultLang["moderator"]));
  lT_Row3_tdLeft.appendChild (document.createElement ("br"));
  lT_Row3_tdLeft.appendChild (moderatorSpan);

  var passInput = document.createElement ("input");
  passInput.setAttribute ("type", config["login"]["password"]["type"]);
  passInput.setAttribute ("name", "password");
  loginWin.node.userForm.elems["password"] = passInput;
  passInput.onkeyup = submitOnEnter;

  setElementSaP (passInput, {"width": config["login"]["password"]["width"] + "px", "class": "textInput"}, null);
  lT_Row3_tdRight.appendChild (passInput);

  if(config["allowLanguage"]){ 
	  var lT_Row4 = addTableRow (loginTable.firstChild, null, null);
	  var lT_Row4_tdLeft = addTableData (lT_Row4, {"width": "40%", "padding": "2px", "textAlign": config["login"]["lang"]["align"]}, null);
	  var lT_Row4_tdRight = addTableData (lT_Row4, {"padding": "2px", "textAlign": "left"}, null);
	
	  var languageSpan = document.createElement ("span");
	  languageSpan.langType = "login"; languageSpan.langStr = "language";
	  languageSpan.appendChild (document.createTextNode (defaultLang["language"]));
	  lT_Row4_tdLeft.appendChild (languageSpan);
	
	  var langSelect = document.createElement ("select");
	  langSelect.setAttribute ("name", "language");
	  loginWin.node.userForm.elems["language"] = langSelect;
	
	  setElementSaP (langSelect, {"width": config["login"]["username"]["width"] + "px"}, null);
	
	  for (key in loginLangs) {
	    var langOpt = document.createElement ("option");
	    langOpt.setAttribute ("value", key);
	
	    if (key == config["defaultLanguage"])
	      langOpt.setAttribute ("selected", "selected");
	
	    langOpt.appendChild (document.createTextNode (loginLangs[key]["name"]));
	
	    langSelect.appendChild (langOpt);
	  }
	
	  langSelect.node = loginWin.node;
	  langSelect.onchange = changeLoginUILanguage;
	
	  lT_Row4_tdRight.appendChild (langSelect);
  }

  loginDoc.appendChild (loginTable);

  /* add the loginDoc to the window content */
  setElementSaP (loginWin.node.contentData, {"textAlign": "center"}, null);

  loginWin.addContent (loginDoc);

  var aaa=addSpanWText (loginDoc, null, null, "test 123");//, "border": "solid #000000 1px"
  
  var loginBtn;
  if (config["login"]["btn"] == "true"){
    loginBtn=loginWin.addButton ("login", "loginBtn", null, actionTypes.OK);
    setElementSaP (loginBtn, null, {"id": "loginBtn"});
    loginBtn.style["float"]="none";
  }

  loginWin.appendToParent (AC_main);

  userInput.focus ();
  return (loginWin);
}

function changeLoginUILanguage () {
  formatUIsLanguage (this.node, this.value, null);
}

function formatUIsLanguage (node, lang, formatInfo) {

  var allSpans = node.getElementsByTagName ("span");

  for (i = 0; i < allSpans.length; i++) {
    var cSpan = allSpans.item (i);

    if (cSpan.langType != null) {
      var newStr = getLanguageString (cSpan.langType, cSpan.langStr, lang, formatInfo);
      if ((cSpan.langType == "dialog") && cSpan.langStr.match ("statuses:"))
        newStr = "(" + newStr + ")";
      cSpan.firstChild.nodeValue = newStr;
    }
  }

  var allInputs = node.getElementsByTagName ("input");
  for (i = 0; i < allInputs.length; i++) {
    var cInput = allInputs.item (i);

    if (cInput.langType != null)
      cInput.setAttribute ("value", getLanguageString (cInput.langType, cInput.langStr, lang, formatInfo));
  }

  var allOptions = node.getElementsByTagName ("option");
  for (i = 0; i < allOptions.length; i++) {
    var cOpt = allOptions.item (i);

    var tNode = cOpt;

    if (tNode.langType != null) {
      var newStr = getLanguageString (tNode.langType, tNode.langStr, lang, formatInfo);
      tNode.firstChild.nodeValue = newStr;
    }
  }

  var statusSelect = document.getElementById ("statusSelect");

  if (statusSelect != null) {
    flushNode (statusSelect);

    statsLang = dialogLang["statuses"];

    for (i = 1; i <= 4; i++) {
      var option = document.createElement ("option");
      option.setAttribute ("value", i);
      option.appendChild (document.createTextNode (statsLang[i]));
      statusSelect.appendChild (option);
    }
  }

  /* TODO */

}

function setSelectOptionByValue (node, val) {
  if (node && (node.tagName.toLowerCase () != "select"))
    return;

  var opts = node.getElementsByTagName ("option");

  for (i = 0; i < opts.length; i++) {
    var copt = opts.item (i);
    if (copt.value == val) {
      if (! browserISIE ())
        copt.selected = true;
      copt.setAttribute ("selected", "selected");
    }
    else {
      if (! browserISIE ())
        copt.selected = false;
      copt.removeAttribute ("selected");
    }
  }
}

function removeSelectOptionByValue (node, val) {
  if (node && (node.tagName.toLowerCase () != "select"))
    return;

  var opts = node.getElementsByTagName ("option");

  for (i = 0; i < opts.length; i++) {
    var copt = opts.item (i);
    if (copt.value == val)
      copt.parentNode.removeChild (copt);
  }
}

function cancelEventPropagation (ev) {
  if (browserISIE ())
    ev.cancelBubble = true;

  if (ev.stopPropagation)
    ev.stopPropagation ();
}

function documentOnClickHandler (e) {

  var cmDiv = document.getElementById ("contextMenu");
  if (! cmDiv)
    return;

  var layoutDiv = document.getElementById ("layoutDiv");
  layoutDiv.removeChild (cmDiv);
}

function doSmileyReplacement (inputString, smileyArray) {
  var newString = inputString;

  /* do :xxx: replacement */
  var reMatch = inputString.match (/\:[a-zA-Z0-9]{2,}\:/g);

  if (reMatch != null) {
    for (i = 0; i < reMatch.length; i++)
      if (smileyArray[reMatch[i]] != null)
        newString = newString.replace (reMatch[i], "<img src=\"" + config["smilesPATH"] + "/" + smileyArray[reMatch[i]] + ".gif\" alt=\"" + smileyArray[reMatch[i]] + "\" />");
  }

  /* do the rest replacements */
  var reMatch = newString.match (/[\:\;8]{1}[-]?[\)\(\!pDs\?]{1}/g);
  if (reMatch != null) {
    for (i = 0; i < reMatch.length; i++)
      if (smileyArray[reMatch[i]] != null)
        newString = newString.replace (reMatch[i], "<img src=\"" + config["smilesPATH"] + "/" + smileyArray[reMatch[i]] + ".gif\" alt=\"" + smileyArray[reMatch[i]] + "\" />");
  }

  return (newString);
}

function doSmileyImage (inputString, smileyArray) {

  var newString = inputString;

  /* do :xxx: replacement */
  var reMatch = inputString.match (/\:[a-zA-Z0-9]{2,}\:/g);

  if (reMatch != null) {
    for (i = 0; i < reMatch.length; i++)
      if (smileyArray[reMatch[i]] != null)
        newString = newString.replace (reMatch[i], config["smilesPATH"] + "/" + smileyArray[reMatch[i]] + ".gif");
  }

  /* do the rest replacements */
  var reMatch = newString.match (/[\:\;8]{1}[-]?[\)\(\!pDs\?]{1}/g);
  if (reMatch != null) {
    for (i = 0; i < reMatch.length; i++)
      if (smileyArray[reMatch[i]] != null)
        newString = newString.replace (reMatch[i], config["smilesPATH"] + "/" + smileyArray[reMatch[i]] + ".gif");
  }

  return (newString);
}

function createSmilesWindow () {
  if(document.getElementById ("smilesList"))
	document.getElementById ("smilesList").removeChild(this);
  		
  var smilesNode = document.createElement ("div");
  if (smilesNode == null)
    return null;

  setElementSaP (smilesNode, null, {"id": "smilesList"});
  config["smiArray"] = new Array ();
  for (var key in config["smiles"]){
	to_insert = 1;
	for (var key2 in config["smiArray"])
		if (config["smiles"][config["smiArray"][key2]]==config["smiles"][key])
			to_insert=0;
	  
	if(to_insert==1)
		config["smiArray"].push(key);
	
  }	
  
  if (config["avatars"])
  	if(user["role"] != config["role"]["ROLE_ADMIN"] && user["role"] != config["role"]["ROLE_MODERATOR"])
	  for (var key in config["avatars"]["mod_only"])
	  	for (i=0;i<config["smiArray"].length;i++)
	    	if(config["smiArray"][i] == config["avatars"]["mod_only"][key]){
		    	config["smiArray"].splice(i,1);
		    	i=config["smiArray"].length;
	    	}
	  	
  var smilesRows = Math.ceil (config["smiArray"].length / (config["smilesPerRow"]));	
  var tableTABLE = document.createElement ("table");
  tableTABLE.setAttribute ("border", "0");
  tableTABLE.setAttribute ("cellspacing", "1");
  tableTABLE.setAttribute ("cellpadding", "0");

  var tableTBODY = document.createElement ("tbody");
  tableTABLE.appendChild (tableTBODY);

  for (i = 0; i < smilesRows; i++) {
    var tmpTR = document.createElement ("tr");

    for (j = 0; j < config["smilesPerRow"]; j++) {
      var tmpTD = document.createElement ("td");

      var currentSmileyKey = config["smiArray"][i * config["smilesPerRow"] + j];
      var currentSmileySrc = config["smilesPATH"] + "/" + config["smiles"][currentSmileyKey] + ".gif";

      if (currentSmileyKey == null)
        continue;

      tmpTD.innerHTML = "<img src=\"" + currentSmileySrc + "\" alt=\"\" title=\"" + currentSmileyKey + "\" onclick=\"generateSmileyCode ('" + currentSmileyKey + "')\" />";

      tmpTR.appendChild (tmpTD);
    }
    tableTBODY.appendChild (tmpTR);
  }

  smilesNode.appendChild (tableTABLE);
  smilesNode.style["visibility"] = "hidden";

  return smilesNode;
}

function generateSmileyCode (code) {
  var smilesNode = document.getElementById ("smilesList");
  if (smilesNode == null)
    return;

  smilesNode.style["visibility"] = "hidden";

  var isForNode = smilesNode.isFor;
  if (! isForNode)
    return;

  if ((isForNode.tagName.toLowerCase () == "input") || (isForNode.tagName.toLowerCase () == "textarea")) {
    isForNode.value += code;
    isForNode.focus ();
  }
  else {
    /* TODO what happens when it's not for an input? */
  }
}

function showSmilesWindow (callerNode, isForNode) {
  var smilesNode = document.getElementById ("smilesList");
  if (smilesNode == null)
    return;

  var divLayout = document.getElementById ("layoutDiv");
  if (divLayout == null)
    return;

  var cNPosition = getTLfromNode (callerNode, divLayout);

  if (smilesNode.style["visibility"] == "hidden") {
	closeAllButtonWindows();
    smilesNode.style["left"] = (cNPosition[0]) + "px";
    smilesNode.style["top"] = (cNPosition[1] - smilesNode.clientHeight - 4) + "px";

    smilesNode.style["visibility"] = "visible";    
  }
  else
    smilesNode.style["visibility"] = "hidden";

  if (isForNode != null)
    smilesNode.isFor = isForNode;
}

function openSFNewWindow (uid, toId, lang, commId) {
  var newURL = "../sharefile.php?userid=" + escape (uid) + "&toid=" + escape (toId) + "&lang=" + escape (lang) + "&connid=" + escape (commId);

  var newWin = window.open (newURL, "_blank", "menubar = no, location = no, resizable = no, status = no, width = 400, height = 250");
}

function openSFDownload (newURL) {
  var newWin = window.open (newURL, "_blank", "menubar = no, location = no, resizable = no, status = no, width = 400, height = 250");
}

function openBrowserWindow (newURL) {
  var newWin = window.open (newURL, "_blank", "menubar = yes, location = yes, resizable = yes, status = yes, scrollbars = yes, toolbar = yes");
}

function openUploadWindow (newURL) {
  var NS = (navigator.appName=="Netscape")?true:false;
  iWidth = (NS)?window.innerWidth:document.body.clientWidth;
  iHeight = (NS)?window.innerHeight:document.body.clientHeight;
  var winl = (screen.width-490)/2;
  var wint = (screen.height-190)/2;
  if (winl < 0) winl = 0;
  if (wint < 0) wint = 0;
  
  var newWin = window.open (newURL, "_blank", "menubar = no, location = no, resizable = no, status = no, width = 490, height = 190, top="+ wint +", left = " + winl);
}

document.onclick = documentOnClickHandler;

