var xmlhttpView;
var xmlhttpPost;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttpView=new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttpPost=new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
    xmlhttpView=new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttpPost=new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttpView=false;
   xmlhttpPost=false;
  }
 }
@else
 xmlhttpView=false;
 xmlhttpPost=false;
 @end @*/
if (!xmlhttpView && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttpView = new XMLHttpRequest();
		xmlhttpPost = new XMLHttpRequest();
	} catch (e) {
		xmlhttpView=false;
		xmlhttpPost = false;
	}
}
if (!xmlhttpView && window.createRequest) {
	try {
		xmlhttpView = window.createRequest();
		xmlhttpPost = window.createRequest();
	} catch (e) {
		xmlhttpView=false;
		xmlhttpPost = false;
	}
}

/* global variables */
var chat2Work = true;
var chat2Busy = false;
var usersOnline;
var chatEntries;
var chat2LastId = 0;
var chat2 = document.getElementById("chat2");
var chat2FirstLoad = true;
var chat2UserId;

var rooms = Array();

function initChat2()
{
  //crate users online room
  var uoRoom = new Chat2Room(1, "Users online");
  uoRoom.createUO();
  rooms.push(uoRoom);
  chat2.appendChild(uoRoom.element);
  
  //create global chat room
  var global = new Chat2Room(0, "NFSUnlimited.net Chat");
  global.createRoom();
  rooms.push(global);
  chat2.appendChild(global.element);
  
  
  autoLoadChat2();
}

function autoLoadChat2()
{
  loadChat2();
  
  if (chat2Work)
    setTimeout("autoLoadChat2()", 15000);
}

function loadChat2()
{
  if (chat2Work && chat2Busy)
  {
    setTimeout("loadChat2()", 250);
  }
  else if (chat2Work)
  {
    var url = '/chat2/chat2Xml.php?lastId=' + chat2LastId + '&rand=' + Math.random()*11;
    
 	  chat2Busy = true;
 	  xmlhttpView.open("GET",url,true);
 	  
 	  
    xmlhttpView.onreadystatechange=function()
  	{
   		if (xmlhttpView.readyState==4)
   		{
        chat2Busy = false;
        var xml = xmlhttpView.responseXML;
        
        var disabled = xml.getElementsByTagName('disabled');
        if (disabled != null && disabled.length == 1)
        {
          chat2Work = false;
          return;
        }
        
        if (chat2FirstLoad)
        {
          document.getElementById("chatFooter").style.display = 'inherit';
          chat2UserId = parseInt(xml.getElementsByTagName('ownUserId')[0].childNodes.item(0).nodeValue);
        }
        
        usersOnline = xml.getElementsByTagName('user');
        chatEntries = xml.getElementsByTagName('entry');
        
        updateChatEntries();
        updateUsersOnline();
        
        chat2FirstLoad = false;
   		}
   	}
    xmlhttpView.send(null);
  }
  
}

function updateChatEntries()
{
  for (var i = 0; i < chatEntries.length; i++)
  {
    var id = parseInt(chatEntries[i].getElementsByTagName("id")[0].childNodes.item(0).nodeValue);
    var userIdFrom = parseInt(chatEntries[i].getElementsByTagName("userIdFrom")[0].childNodes.item(0).nodeValue);
    var userIdTo = parseInt(chatEntries[i].getElementsByTagName("userIdTo")[0].childNodes.item(0).nodeValue);
    var usernameFrom = chatEntries[i].getElementsByTagName("usernameFrom")[0].childNodes.item(0).nodeValue;
    var usernameTo = chatEntries[i].getElementsByTagName("usernameTo")[0].childNodes.item(0).nodeValue;
    var date = chatEntries[i].getElementsByTagName("date")[0].childNodes.item(0).nodeValue;
    var dateText = chatEntries[i].getElementsByTagName("dateText")[0].childNodes.item(0).nodeValue;
    var text = chatEntries[i].getElementsByTagName("text")[0].childNodes.item(0).nodeValue;
    
    //update lastId
    if (id > chat2LastId)
    {
      chat2LastId = id;
    }
    
    var roomId = 0;
    var roomTitle = "";
    
    if (userIdTo != 0)
    {
      if (userIdTo == chat2UserId)
      {
        roomId = userIdFrom;
        roomTitle = usernameFrom;
      }
      else
      {
        roomId = userIdTo;
        roomTitle = usernameTo;
      }
    }
      
    //init the chatroom if it doesn't yet exist
    var room = null;
    for (var j = 0; j < rooms.length; j++)
    {
      if (rooms[j].id == roomId)
      {
        room = rooms[j];
        break;
      }
    }
    
    if (room == null)
    {
      room = new Chat2Room(roomId, roomTitle);
      room.createRoom();
      rooms.push(room);
      if (!chat2FirstLoad)
        room.show();
      chat2.appendChild(room.element);
    }
    
    room.addEntry(id, userIdFrom, usernameFrom, date, dateText, text);
  }
}

function updateUsersOnline()
{
  var uoBox = rooms[0].msgBox;
  
  //clear the box
  if (uoBox.hasChildNodes())
  {
    while (uoBox.childNodes.length >= 1)
    {
      uoBox.removeChild(uoBox.firstChild);       
    } 
  }
  
  for (var i = 0; i < rooms.length; i++)
  {
    rooms[i].setOffline();
  }
  
  //add all the users from the xml
  for (var i = 0; i < usersOnline.length; i++)
  {
    var username = usersOnline[i].getElementsByTagName("username")[0].childNodes.item(0).nodeValue;
    var userId = parseInt(usersOnline[i].getElementsByTagName("id")[0].childNodes.item(0).nodeValue);
    var country = (usersOnline[i].getElementsByTagName("country")[0].childNodes.length > 0 ? usersOnline[i].getElementsByTagName("country")[0].childNodes.item(0).nodeValue : "");
    
    var uoUserBox = document.createElement("div");
    var userLink = document.createElement("a");
    userLink.setAttribute("href", "");
    userLink.setAttribute("onclick", "openChat2(" + userId + ", '" + username + "'); return false;");
    
    if (country != "")
    {
      var countryEl = document.createElement("img");
      countryEl.setAttribute("src", "http://www.nfsunlimited.net/images/countries/" + country.toLowerCase() + ".gif");
      countryEl.setAttribute("alt", country);
      userLink.appendChild(countryEl);
    }
    
    userLink.appendChild(document.createTextNode(" " + username));
    uoUserBox.appendChild(userLink);
    
    uoBox.appendChild(uoUserBox);
    
    for (var j = 0; j < rooms.length; j++)
    {
      if (rooms[j].id == userId)
      {
        rooms[j].setOnline();
        break;
      }
    }
  }
  
  rooms[0].setTitle("Users online (" + usersOnline.length + ")");
}


function chat2Post(e, id, textarea)
{
  var characterCode;

  if(e && e.which)
  {
    e = e
    characterCode = e.which;
  }
  else
  {
    e = event
    characterCode = e.keyCode;
  }
  
  if(characterCode == 13)
  {
    var message = textarea.value;
    
    xmlhttpPost.open("POST",'/chat2/chat2Xml.php',true);
 	  
    xmlhttpPost.onreadystatechange=function()
  	{
   		if (xmlhttpPost.readyState==4)
   		{
        textarea.value = '';
        var xml = xmlhttpPost.responseXML;
        
        usersOnline = xml.getElementsByTagName('user');
        chatEntries = xml.getElementsByTagName('entry');
        
        updateUsersOnline();
        updateChatEntries();
   		}
   	}
   	xmlhttpPost.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    xmlhttpPost.send('postId=' + id + '&postText=' + escape(message) + "&lastId=" + chat2LastId);
  }
}

function chat2Enlarge(id)
{
  for (var i = 0; i < rooms.length; i++)
  {
    var enlargedRoom = rooms[i].element.getElementsByTagName("div")[0];
    if (rooms[i].id == id && rooms[i].hidden)
    {
      rooms[i].show();
    }
    else if (rooms[i].id == id)
    {
      rooms[i].hide();
    }
  }
}

function openChat2(id, title)
{
  var room;
  for (var i = 0; i < rooms.length; i++)
  {
    if (rooms[i].id == id)
    {
      room = rooms[i];
      room.show();
      break;
    }
  }
  
  if (room == null)
  {
    room = new Chat2Room(id, title);
    room.createRoom();
    rooms.push(room);
    room.show();
    chat2.appendChild(room.element);
  }
}

function closeChat2(id)
{
  var room;
  for (var i = 0; i < rooms.length; i++)
  {
    if (rooms[i].id == id)
    {
      room = rooms[i];
      rooms.splice(i, 1);
      break;
    }
  }
  
  chat2.removeChild(room.element);
  
  xmlhttpPost.open("POST",'/chat2/chat2Xml.php',true);
 	  
  xmlhttpPost.onreadystatechange=function()
	{
 		if (xmlhttpPost.readyState==4)
 		{
      textarea.value = '';
      var xml = xmlhttpPost.responseXML;
      
      usersOnline = xml.getElementsByTagName('user');
      chatEntries = xml.getElementsByTagName('entry');
      
      updateUsersOnline();
      updateChatEntries();
 		}
 	}
 	xmlhttpPost.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
  xmlhttpPost.send('closeRoom=' + id + "&lastId=" + chat2LastId);
  
  //room = null;
}

function chat2FormatTime(date)
{
  var curDate = new Date();
  curDate.setHours(0);
  curDate.setMinutes(0);
  curDate.setSeconds(0);
  
  var result = "";
  if (date < curDate)
  {
    var numDays = Math.floor((curDate.getTime() - date.getTime()) / 86400000);
    if (numDays == 0)
      result += "Yesterday, ";
    else if (numDays > 0)
      result += (numDays + 1) + " days ago, ";
  }
  
  if (date.getHours() < 10) result += "0";
  result += date.getHours() + ":";
  if (date.getMinutes() < 10) result += "0";
  result += date.getMinutes() + ":";
  if (date.getSeconds() < 10) result += "0";
  result += date.getSeconds();
  return result;
}


function Chat2Room(id, title)
{
  this.id = id;
  this.title = (title.length > 18 && id > 0 ? title.substring(0, 16) + "..." : title);
  var element;
  var msgBox;
  this.hidden = true;
  var onlineButton;
  var linkContainer;
  this.elementWidth = (this.title.length * 7 + 30 > 158 ? 158 : (this.title.length * 7 + 30)) + "px";;
  
  this.createRoom = function()
  {
    this.element = document.createElement("div");
    this.element.setAttribute("class", "chat2Room");
    
    var enlarged = document.createElement("div");
    enlarged.setAttribute("class", "chat2RoomHidden");
    enlarged.setAttribute("id", "chat2RoomE" + this.id);
    
    this.msgBox = document.createElement("div");
    this.msgBox.setAttribute("class", "chat2RoomMsgBox");
    this.msgBox.setAttribute("id", "chat2RoomMsgBox" + this.id);
    enlarged.appendChild(this.msgBox);
    
    var inputBox = document.createElement("div");
    inputBox.setAttribute("class", "chat2RoomInputBox");
    
    var textarea = document.createElement("textarea");
    textarea.setAttribute("onkeypress", "chat2Post(event, '" + this.id + "', this);");
    inputBox.appendChild(textarea);
    
    enlarged.appendChild(inputBox);
    
    this.element.appendChild(enlarged);
    
    var titleEl = document.createElement("div");
    titleEl.setAttribute("class", "chat2RoomTitle");
    
    this.linkContainer = document.createElement("div");
    this.linkContainer.setAttribute("class", "chat2RoomTitleLink");
    this.linkContainer.style.width = this.elementWidth;
    
    var linkEl = document.createElement("a");
    linkEl.setAttribute("id", "chat2RoomTitle" + this.id);
    linkEl.setAttribute("onclick", "chat2Enlarge(" + this.id + "); return false;");
    linkEl.setAttribute("href", "");
    
    if (this.id > 0)
    {
      this.onlineButton = document.createElement("img");
      this.onlineButton.setAttribute("src", "http://www.nfsunlimited.net/chat2/chat2Online.png");
      this.onlineButton.setAttribute("alt", "online");
      this.onlineButton.setAttribute("class", "chat2OnlineButton");
      linkEl.appendChild(this.onlineButton);
    }
    
    var linkTitle = document.createTextNode(this.title);
    linkEl.appendChild(linkTitle);
    this.linkContainer.appendChild(linkEl);
    
    titleEl.appendChild(this.linkContainer);
    
    if (this.id > 1)
    {
      var closeContainer = document.createElement("div");
      closeContainer.setAttribute("class", "chat2Close");
      var closeEl = document.createElement("a");
      closeEl.setAttribute("href", "");
      closeEl.setAttribute("onclick", "closeChat2(" + this.id + "); return false;");
      var closeImg = document.createElement("img");
      closeImg.setAttribute("src", "http://www.nfsunlimited.net/images/icons/close.gif");
      closeImg.setAttribute("alt", "close");
      closeEl.appendChild(closeImg);
      closeContainer.appendChild(closeEl);
      titleEl.appendChild(closeContainer);
    }
    
    this.element.appendChild(titleEl);
  }
  
  this.createUO = function()
  {
    this.element = document.createElement("div");
    this.element.setAttribute("class", "chat2Room");
    
    var enlarged = document.createElement("div");
    enlarged.setAttribute("class", "chat2RoomHidden");
    enlarged.setAttribute("id", "chat2RoomE" + id);
    
    this.msgBox = document.createElement("div");
    this.msgBox.setAttribute("class", "chat2RoomUOBox");
    this.msgBox.setAttribute("id", "chat2RoomUOBox");
    enlarged.appendChild(this.msgBox);
    
    this.element.appendChild(enlarged);
    
    var titleEl = document.createElement("div");
    titleEl.setAttribute("class", "chat2RoomTitle");
    
    this.linkContainer = document.createElement("div");
    this.linkContainer.setAttribute("class", "chat2RoomTitleLink");
    var linkEl = document.createElement("a");
    linkEl.setAttribute("id", "chat2RoomTitle" + this.id);
    linkEl.setAttribute("onclick", "chat2Enlarge(" + this.id + "); return false;");
    linkEl.setAttribute("href", "");
    linkEl.innerHTML = this.title;
    this.linkContainer.appendChild(linkEl);
    
    titleEl.appendChild(this.linkContainer);
    this.element.appendChild(titleEl);
  }
  
  this.setTitle = function(newTitle)
  {
    this.title = newTitle;
    var linkEl = document.getElementById("chat2RoomTitle" + this.id);
    linkEl.innerHTML = this.title;
  }
  
  this.show = function()
  {
    this.element.getElementsByTagName("div")[0].className = "chat2RoomEnlarged";
    this.linkContainer.style.width = "158px";
    this.hidden = false;
  }
  
  this.hide = function()
  {
    this.element.getElementsByTagName("div")[0].className = "chat2RoomHidden";
    this.linkContainer.style.width = this.elementWidth;
    this.hidden = true;
  }
  
  this.addEntry = function(id, userIdFrom, usernameFrom, date, dateText, text)
  {
    if (this.hidden == true && !chat2FirstLoad)
      this.show();
    
    var entry = document.createElement("div");
    var entryHeader = document.createElement("div");
    entryHeader.setAttribute("class", "chat2EntryHeader");
    
    var userFrom = document.createElement("a");
    userFrom.setAttribute("href", "");
    userFrom.setAttribute("onclick", "chat2Enlarge(" + userIdFrom + ");return false;");
    userFrom.innerHTML = usernameFrom;
    entryHeader.appendChild(userFrom);
    
    var d = new Date();
    d.setTime(date * 1000);
    
    var datePost = document.createElement("p");
    datePost.setAttribute("class", "chat2EntryDate");
    datePost.innerHTML = chat2FormatTime(d);
    entryHeader.appendChild(datePost);
    
    var entryText = document.createElement("div");
    entryText.setAttribute("class", "chat2EntryText");
    entryText.innerHTML = text;
    
    entry.appendChild(entryHeader);
    entry.appendChild(entryText);
    
    //insert it to the top
    var curEntries = this.msgBox.getElementsByTagName("div");
    if (curEntries.length > 0)
      this.msgBox.insertBefore(entry, curEntries[0]);
    else
      this.msgBox.appendChild(entry);
  }
  
  this.setOffline = function()
  {
    if (this.id > 1)
      this.onlineButton.setAttribute("src", "http://www.nfsunlimited.net/chat2/chat2Offline.png");
  }
  
  this.setOnline = function()
  {
    if (this.id > 1)
      this.onlineButton.setAttribute("src", "http://www.nfsunlimited.net/chat2/chat2Online.png");
  }
}

initChat2();
