var gamers = new Array(); // here store list of gamers

var chat = new Array(); // here store messages from chat

var p = 0; // `points` - to show that connection is `live`

var pnew = 1; // Sends to server when pinging. If set to 1 then server returns ALL data, 
        //  oterwise just changed
var uid=-1;

function initChat(){
  if ($("#chat").attr('class') == undefined) return;
  $("input", $("#chat_init_messages")).each(function(){
      addchatmessage($(this).attr('dtcreated'), $(this).attr('howtowrite'), $(this).attr('message'));
  });
// Define user's UID
  if ($("#window_head").attr('uid') != undefined){
    uid = $("#window_head").attr('uid');

  }
  
  $("input", $("#chat_init_users")).each(function(){
      addnewplayer($(this).attr('userid'), $(this).attr('username'), 0, $(this).attr('howtowrite'));
  });
  drawgamerstable();
  function ping(){
    $.post(
      '/index.php',
      {
        paction:'chat_ping',
        pnochat:'asd'
      
      },
      function(data){
        if (pnew == 1){
          $("#hideall").css("display", "block");
          $("#pleasewait").css("display", "none");
        }
        pnew = 0;
        p = (p+1)%4;
        
        if (p==3) $("#ping").empty().html('.');
        else $("#ping").append('.');
// So, we get some chat message       
        var query=new Array();
        $("root > chat > message", data).each(function(){
          if ($(this).attr('uid')!=uid){
            if ($(this).text() != undefined){
              query[query.length] = {         
                dtcreated: $(this).attr('dtcreated'),
                user: $(this).attr('htw'),
                message: $(this).text()
              };
            }
          }
          
        });
        
        for (i=query.length-1; i>=0; i--){
          addchatmessage(query[i].dtcreated, query[i].user, query[i].message);
        }
// Now draw new gamers and remove old
        changed = 0;
        $("newplayers", $("root > players", data)).each(function(){
          addnewplayer($(this).attr('uid'), $(this).attr('name'), 0, $(this).attr('htw'));
          changed = 1;
        });
        $("root > players > remove", data).each(function(){
        
          removeplayer($(this).attr('uid'));
          changed = 1;
        });
        if (changed !=0)
          drawgamerstable();
        setTimeout(ping, 1000);
        
        
      }
    
    );
  } 
  ping();
// Just send message to chat  
  $("#say_ok").click(function(){
    var wts = '';
    if ($("#say").attr('value') !=undefined ){
      wts = $("#say").attr('value');
      d = new Date();
      h = d.getHours();
      m = d.getMinutes();
      addchatmessageY(wts); 
    }
    if ((wts!=undefined) && (wts!='') ){
      $.post(
        '/index.php',
        {
          paction:'chat_say',
          pnochat:'nochat',
          psay:wts
        },
        function(data){
        
        }
      );
    }
    $("#say").attr('value', '');
  });
  $("#say").keydown(function(event){
      
      if (event.keyCode == 13){
        $("#say_ok").click();
      }
  });
}
// function draws new message into chat window
function addchatmessage(dtcreated, user, message){
  tmp = ""; 
  if ($("#chat").html() != undefined)
    tmp = $("#chat").html();
  tmp = "<span class=\"date\">"+dtcreated+"</span> <span class=\"user\">"+user+"</span> <span class=\"message\">"+message+"</span><br />"+tmp;
  $("#chat").html(tmp);
}

// function draws new message into chat window
function addchatmessageY(message){
  tmp = ""; 
  if ($("#chat").html() != undefined)
    tmp = $("#chat").html();
  tmp = "<span class=\"chat_owner\">"+message+"</span><br />"+tmp;
  $("#chat").html(tmp);
}
// function add new player to the players' list
function addnewplayer(id, name, rank, htw){
  gamers[gamers.length] = {
    id: id,
    name:name,
    htw:htw
  }   
  
  
}
// function removes player
function removeplayer(uid){
  k=-1;
  for (i=0; i<gamers.length; i++){
    if (gamers[i].id == uid) {
      k=i;
      break;
    }
  }
  if (k == -1) return;
  
  gamers.splice(k, 1);
  
}
// shows online players
function drawgamerstable(){
  ret = "";
  for (i=0; i<gamers.length; i++){
    ret += '<tr><td align="center">'+gamers[i].htw+'</td></tr>';
  }
  ret = '<table align="center">'+ret+'</table>';
  $("#online").html(ret);
}
initChat();