var last_message = 0;
var last_color = "#FFFFFF";
function rand(l,u) {
return Math.floor((Math.random() * (u-l+1))+l);
}
function last_msg_color() {
        if(last_color == "#FFFFFF") {
                last_color = "#EAFAF6";
        } else {
                last_color = "#FFFFFF";
        }
}
function smiley_msg(msg) {
        var new_smiley_msg = msg.replace(/:\)/g,"<img src='/images/chat_emote_smile.png'>").replace(/XD/g,"<img src='/images/chat_emote_evilgrin.png'>").replace(/:D/g,"<img src='/images/chat_emote_grin.png'>").replace(/:O/g,"<img src='/images/chat_emote_surprised.png'>").replace(/:P/g,"<img src='/images/chat_emote_tongue.png'>").replace(/:\(/g,"<img src='/images/chat_emote_unhappy.png'>").replace(/;\)/g,"<img src='/images/chat_emote_wink.png'>").replace(/:o/g,"<img src='/images/chat_emote_surprised.png'>").replace(/:p/g,"<img src='/images/chat_emote_tongue.png'>");
        return new_smiley_msg;
}
function refreshUsers() {
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
        var ajaxDisplay = document.getElementById('chatters');
                if(ajaxRequest.readyState == 4){
                        if (ajaxRequest.status == 200) {
                        var response = ajaxRequest.responseText;
var checkKick = response.split('user_has_been_kicked_from_chatroom-').join('check');
                                if(checkKick != response) {
document.getElementById('chatroom').style.display = "none";
document.getElementById('kickedFromChat').style.display = "block";
document.getElementById('kickedFromChat').innerHTML = "<div style='margin: 15px;background-color: #FFFFFF;padding: 5px;'><center><br />You have been kicked from the chatroom!<br /><br /><b>"+ response.split('user_has_been_kicked_from_chatroom-').join('') +" left</b><br /><br />An Admin/Moderator has kicked you from the chatroom. If you believe there wasn't a legit reason for them kicking you, please <a href='/contactus.php'>contact us</a> and we will look at the person who kicked you and why. If this wasn't a legit kick, immediate action will be taken and you will be unkicked from the chat.<br /></div>";
document.getElementById('was_kicked').value = "yes";
                                } else
if(document.getElementById('was_kicked').value == "yes") {
document.getElementById('chatroom').style.display = "block";
document.getElementById('kickedFromChat').style.display = "none";
                                document.getElementById('kickedFromChat').innerHTML = "<div style='margin: 10px;background-color: #FFFFFF;'><center><br />You can now to return to the chatroom...<br />And this time, don't get kicked!<br /><br /><a href='javascript:;' onClick=\"window.location='"+ window.location.href +"'\">Click here to refresh the Game Page</a></div>";
                                }
                                var TO1 = setTimeout("refreshUsers()", 3000);
                                //refreshUsers();
                                if(document.getElementById('chatters_loaded').value == "no") {
                                document.getElementById('chatters_loaded').value = "yes";
                                }
                                ajaxDisplay.innerHTML = ajaxRequest.responseText;
                        }

                }
        }
        var current_game = document.getElementById('current_game').value;
        ajaxRequest.open("GET", "/gamechat.php?mode=receive&action=refreshing&current_game="+ current_game +"&rand="+ rand(1,10000), true);
        ajaxRequest.send(null);
}
function refreshMessages(init) {
if(init != 0) {
        $.ajax({
          url: "/i/gchat_inc/last_msg.txt",
          cache: false,
          dataType: "json",
          success: function(data) {
                last_message = data;
                document.getElementById('chatmsgs_loaded').value = "yes";
          }
        });
        refreshMessages(0);
} else {
        $.ajax({
          url: "/i/gchat_inc/last_msg.txt",
          cache: false,
          dataType: "json",
          success: function(data) {
                if((data*1) > (last_message*1)) {
                        last_message = data;
                        refreshMessages_retrieve();
                } else {
                        refreshMessages(0);
                }
          }
        });
}
}
function refreshMessages_retrieve() {
var new_msgs_block = "";
$.ajax({
url: "/gamechat.php?mode=receive&action=getMessages&rand="+ rand(1,10000),
cache: false,
dataType: "json",
error: function(thrownError) {
$('#chatmsgs').html($('#chatmsgs').html() + "<div style=\"background-color: #EEEEEE;\"><i>Chat connection error, could not gain clear connection the game chat:<br />"+thrownError+"<br />New connection has been created.</i></div>");
document.getElementById('chatmsgs').scrollTop = 500000;
refreshMessages(0);
},
success: function(data) {
if(data) {
if(data.is_new == 1) {
var new_msgs_block = "";
$.each(data.new_msgs, function(i,new_msgs) {
if(new_msgs.type == "server") {
new_msgs_block = new_msgs_block +"<div style=\"background-color: "+last_color+";padding: 2px;\"><span style=\"font-size: 12px;color: #A3A3A3;font-weight: bold;\">"+new_msgs.msg+"</span></div>";
} else if(new_msgs.type == "user") {
var msg = new_msgs.msg;
new_msgs_block = new_msgs_block +"<div style=\"background-color: "+last_color+";padding: 2px;\"><span style=\"font-size: 12px;\"><a href=\"javascript:;\" onClick=\"miniProfile('"+new_msgs.uid+"');\" style=\"color: #0000FF;\">"+new_msgs.uname+"</a>: "+msg+"</span></div>";
}
last_msg_color();
});
$('#chatmsgs').html($('#chatmsgs').html() + new_msgs_block);
document.getElementById('chatmsgs').scrollTop = 500000;
}
}
refreshMessages(0);
}
});
}
function addMessage() {
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        if (ajaxRequest.status == 200) {
                        //document.getElementById('chat_textarea').value = "";
                        //document.getElementById('chat_textarea').focus();
                        //document.getElementById('message_status').innerHTML = "<img src='/images/chat_icon_sent.png' title='Message sent!'>";
                        //document.addMessage.disabled = false;
                        //document.getElementById('chat_textarea').disabled = false;
                        }

                }
        }
        var message = document.getElementById('chat_textarea').value;
        if(message == "" || message.split(' ').join('') == "") {
        } else {
        //document.getElementById('message_status').innerHTML = "<img src='/images/chat_icon_sending.gif' title='Sending...'>";
        //document.addMessage.disabled = true;
        //document.getElementById('chat_textarea').disabled = true;
        ajaxRequest.open("GET", "/gamechat.php?mode=receive&action=addMessage&message="+ message +"&rand="+ rand(1,10000), true);
        ajaxRequest.send(null);
        document.getElementById('chat_textarea').value = "";
        document.getElementById('chat_textarea').focus();
        var show_self_msg = "<div style=\"background-color: "+last_color+";padding: 2px;\"><span style=\"font-size: 12px;\"><b>Me</b>: "+smiley_msg(message)+"</span></div>";
        var new_rand = rand(1,100000);
        var new_message = "<div id=\"msg_rand"+new_rand+"\" style=\"//background-color: #F5FF9E;\">"+show_self_msg+"</div>";
        $('#chatmsgs').html($('#chatmsgs').html()+ new_message);
        document.getElementById('chatmsgs').scrollTop = 500000;
        last_msg_color();
        }
}

function kickUser() {
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        if (ajaxRequest.status == 200) {
                                if(ajaxRequest.responseText == "kicked") {
                                var screenTimeoutID = setTimeout("screenMessage('User has been kicked!','<center>User has been kicked from the chatroom.</center>','show')", 3000);
                                } else if(ajaxRequest.responseText == "not_allowed") {
                                screenMessage("","","hide");
                                alert('You are not an Admin/Moderator therefore you do not have the permission to kick users from the chatroom');
                                }
                        }
                }
        }
var toKick = document.getElementById('toKick').value;
var reason = document.getElementById('reason').value;
var length = document.getElementById('length').value;
        ajaxRequest.open("GET", "/gamechat.php?mode=receive&action=kickUser&reason="+ reason +"&toKick="+ toKick +"&length="+ length +"&rand="+ rand(1,10000), true);
        ajaxRequest.send(null);
var username = document.getElementById('toKickUsername').value;
screenMessage("Kicking user...","<center><b>Please wait... Kicking "+ username +" from the chatroom...</b><br />This may take a few seconds.<br /><br /><img src='/images/loading_big-circle.gif'></center>","show");
}

function kickUserForm(toKick,username) {
screenMessage("Kick User from Chatroom","<center><b>Need to kick a user from the Chatroom?</b><br />Your reason for kicking them must be that they are breaking a rule. If you abuse this feature, action will be taken to make sure you can't abuse it anymore.<br />Fill out the form below to kick the user. User will be kicked immediately upon submit.<br /><br /><table border='0' width='60%' cellspacing='5'><tr><td valign='top' align='left'><b>Username:</b></td><td valign='top' align='left'>"+ username +"</td></tr><tr><td valign='top' align='left'><b>Length:</b></td><td valign'top' align='left'><select name='length' id='length'><option value='60'>1 minute</option><option value='300'>5 minutes</option><option value='900'>15 minutes</option><option value='1800'>30 minutes</option><option value='3600'>1 hour</option><option value='7200'>2 hours</option><option value='21600'>6 hours</option><option value='43200'>12 hours</option><option value='86400'>1 day</option></select></td></tr><tr><td valign='top' align='left'><b>Reason:</b></td><td valign='top' align='left'><textarea rows='5' cols='50' id='reason'></textarea></td></tr></table><input type='hidden' id='toKickUsername' value='"+ username +"'><input type='hidden' id='toKick' value='"+ toKick +"'><br /><br /><input type=\"button\" value=\"Submit\" onClick=\"kickUser();\">","show");
}

function miniProfile(uid) {
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        if (ajaxRequest.status == 200) {
                                document.getElementById('miniProfile').innerHTML = ajaxRequest.responseText;
                        }

                }
        }
        document.getElementById('chatroom').style.display = "none";
        document.getElementById('miniProfile_wrapper').style.display = "block";
        document.getElementById('miniProfile').innerHTML = "<div style='margin-left: 10px;margin-right: 10px;width: 280px;margin-top: 5px;background-color: #FFFFFF;'><center><br /><b>Loading... Please Wait...</b><br /><br /><img src='/images/loading_big-circle.gif'></center><br /></div>";
        ajaxRequest.open("GET", "/gamechat.php?mode=receive&action=miniProfile&userID="+ uid +"&rand="+ rand(1,10000), true);
        ajaxRequest.send(null);
}

function closeMiniProfile() {
document.getElementById('chatroom').style.display = "block";
document.getElementById('miniProfile_wrapper').style.display = "none";
}

function initializeChat() {
var noChatLogin = document.getElementById('noChatLogin').value;
var chatters_loaded = document.getElementById('chatters_loaded').value;
var chatmsgs_loaded = document.getElementById('chatmsgs_loaded').value;
//if(chatters_loaded == "no" || chatmsgs_loaded == "no") {
if(chatters_loaded == "no") {
var reInitializeChat = setTimeout("initializeChat()", 1000);
} else {
document.getElementById('chatroomBody').style.display = "block";
document.getElementById('doChatLoad').style.display = "none";
if(noChatLogin == "logged_in") {
document.getElementById('textbox').style.display = "block";
document.getElementById('textbox_noLogin').style.display = "none";
} else {
document.getElementById('textbox').style.display = "none";
document.getElementById('textbox_noLogin').style.display = "block";
}
}
}

/* 

Script to gradually change background colour of an element

References: 
   http://www.37signals.com/svn/archives/000558.php
   http://www.meyerweb.com/eric/tools/color-blend/

Future work: 
   Could change foreground, border colours
   Transparency

*/

function ChatFade(id, startColour, endColour, count, speed, delay ) {

  /* Properties */

  this.id = id;                    /* id/object ref of element to fade */
  this.startColour = startColour;  /* initial colour (3 or 6 digit) hex */
  this.endColour = endColour;      /* final colour (3 or 6 digit) hex */
  this.count = count;              /* No of steps to take during fade */
  this.speed = speed;              /* Delay in ms between steps */
  this.delay = delay;              /* Initial delay before fade begins */

  if (typeof this.id == "string") {
    this.obj = document.getElementById(id);  
  } else {
    this.obj = this.id;
  }
  this.colour = new Array();
  this.steps = 0;

  /* Methods */

  this.init = init;
  this.fade = fade;
  this.parseColour = parseColour;

  function init() {

    first = this.parseColour(this.startColour, 'hex');
    last = this.parseColour(this.endColour, 'hex');

    this.colour = new Array();
    this.colour[this.count] = this.startColour;
    for (i=0; i<this.count; i++) {
      temp = "rgb(";
      temp += parseInt(first[0]+(last[0]-first[0])/this.count*i);
      temp += ",";
      temp += parseInt(first[1]+(last[1]-first[1])/this.count*i);
      temp += ",";
      temp += parseInt(first[2]+(last[2]-first[2])/this.count*i);
      temp += ")";
      this.colour[this.count-i] = temp;
    }
    this.colour[0] = this.endColour;

    var thisObj = this;
    setTimeout( function() { thisObj.fade() }, this.delay);

  }

  function fade() {
      
    if (this.count >= 0) {

      this.obj.style.backgroundColor = this.colour[this.count--];

      // I want to do this:
      // setTimeout("this.fade()", init.speed);
      // but setTimeout runs in a different thread so 'this' 
      // is out of context. 
      // See: http://www.faqts.com/knowledge_base/view.phtml/aid/2311

      var thisObj = this;
      setTimeout( function() { thisObj.fade() }, this.speed);

    }
  }

  function parseColour(colour, t) {
    /* From: http://www.meyerweb.com/eric/tools/color-blend/ */
    var m = 1;
    col = colour.replace(/[\#rgb\(]*/,'');
    if (t == 'hex') {
      if (col.length == 3) {
        a = col.substr(0,1);
        b = col.substr(1,1);
        c = col.substr(2,1);
        col = a + a + b + b + c + c;
      }
      var num = new Array(col.substr(0,2),col.substr(2,2),col.substr(4,2));
      var base = 16;
    } else {
      var num = col.split(',');
      var base = 10;
    }
    if (t == 'rgbp') {m = 2.55}
    var ret = new Array(parseInt(num[0],base)*m,parseInt(num[1],base)*m,parseInt(num[2],base)*m);
    return(ret);
  }
}

function GSK_switchTab(id) {
if(id == "chatroom") {
if(document.getElementById('was_kicked').value == "no") {
document.getElementById('chatroom').style.display = "block";
document.getElementById('kickedFromChat').display = "none";
} else {
document.getElementById('chatroom').display = "none";
document.getElementById('kickedFromChat').display = "block";
}
document.getElementById('gameinfo').style.display = "none";
document.getElementById('moregames').style.display = "none";
document.getElementById('miniProfile_wrapper').style.display = "none";
document.getElementById('GSK_chatroom_tab').className = "GSK_tab_opened";
document.getElementById('GSK_gameinfo_tab').className = "GSK_tab_closed";
document.getElementById('GSK_moregames_tab').className = "GSK_tab_closed";
} else if(id == "gameinfo") {
document.getElementById('chatroom').style.display = "none";
document.getElementById('kickedFromChat').display = "none";
document.getElementById('gameinfo').style.display = "block";
document.getElementById('chatroom').style.display = "none";
document.getElementById('moregames').style.display = "none";
document.getElementById('miniProfile_wrapper').style.display = "none";
document.getElementById('GSK_gameinfo_tab').className = "GSK_tab_opened";
document.getElementById('GSK_chatroom_tab').className = "GSK_tab_closed";
document.getElementById('GSK_moregames_tab').className = "GSK_tab_closed";
} else if(id == "moregames") {
document.getElementById('moregames').style.display = "block";
document.getElementById('chatroom').style.display = "none";
document.getElementById('kickedFromChat').display = "none";
document.getElementById('gameinfo').style.display = "none";
document.getElementById('miniProfile_wrapper').style.display = "none";
document.getElementById('GSK_moregames_tab').className = "GSK_tab_opened";
document.getElementById('GSK_chatroom_tab').className = "GSK_tab_closed";
document.getElementById('GSK_gameinfo_tab').className = "GSK_tab_closed";
}
}

function chat_userOver(link,span,content)
{
document.getElementById('userRehovered').value = "yes";
document.getElementById('userHover_body').innerHTML = content;
var span_width = document.getElementById(span).offsetWidth;
var span_height = document.getElementById(span).offsetHeight;
var link_offsetTop = link.offsetTop;
var openDiv = document.getElementById('userHover_wrapper');
if(openDiv.style.visiblity != "visible") {
openDiv.style.left = span_width + findPosX(link) + 15 +"px";
openDiv.style.visibility = "visible";
openDiv.style.display = "block";
var openDiv_height = openDiv.offsetHeight;
//var doMeasure = openDiv_height / 2;
//var doMeasure = doMeasure - (span_height / 2);
//var doMeasure = findPosY(link) - doMeasure;
var doMeasure = findPosY(link) - (span_height / 2) + 2;
openDiv.style.top = doMeasure +"px";
}
}
function chat_userOut_trigger() {
if(document.getElementById('userIsHovering').value == "no") {
document.getElementById('userRehovered').value = "no";
setTimeout("chat_userOut_attempt()", 500);
}
}
function chat_userOut_attempt()
{
if(document.getElementById('userIsHovering').value == "no") {
chat_userOut_do();
}
}
function chat_userOut_do() {
if(document.getElementById('userRehovered').value == "no") {
var openDiv = document.getElementById('userHover_wrapper');
openDiv.style.visibility = "hidden";
openDiv.style.display = "none";
}
}
function chat_userMouseover() {
document.getElementById('userIsHovering').value = "yes";
}
function chat_userMouseout() {
document.getElementById('userIsHovering').value = "no";
chat_userOut_trigger();
}
